<?php
// api/add_client_with_plot.php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

header('Content-Type: application/json');
header('Access-Control-Allow-Origin', '*');
header('Access-Control-Allow-Methods', 'POST, OPTIONS');
header('Access-Control-Allow-Headers', 'Content-Type');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(204);
    echo json_encode(['status' => 'ok']);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'message' => 'Method not allowed']);
    exit;
}

require_once __DIR__ . '/../../config.php';

// PHPMailer includes
require_once __DIR__ . '/../PHPMailer-7.0.0/src/Exception.php';
require_once __DIR__ . '/../PHPMailer-7.0.0/src/PHPMailer.php';
require_once __DIR__ . '/../PHPMailer-7.0.0/src/SMTP.php';

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

/**
 * Reusable mailer factory for Safe Step with:
 * - short timeouts
 * - debug logged to smtp_debug_bam.log
 */
function createVillacoMailer(): PHPMailer {
    $mail = new PHPMailer(true);
    $mail->isSMTP();
    $mail->Host       = 'smtp.gmail.com';
    $mail->SMTPAuth   = true;
    $mail->Username   = 'muntari.audullahi@gmail.com';
    $mail->Password   = 'qhtonveqpfituqtn';
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
    $mail->Port       = 587;
    $mail->CharSet    = 'UTF-8';

    // Prevent long blocking
    $mail->Timeout       = 10;
    $mail->SMTPKeepAlive = false;

    // Log SMTP conversation for later debugging
    $mail->SMTPDebug  = 0;
    $mail->Debugoutput = function($str, $level) {
        file_put_contents(
            __DIR__ . '/smtp_debug_bam.log',
            date('Y-m-d H:i:s') . " [$level] $str\n",
            FILE_APPEND
        );
    };

    $mail->setFrom('muntari.audullahi@gmail.com', 'Safe Step Properties Limited');
    $mail->isHTML(true);

    return $mail;
}

// Client portal URL for tracking contract, payments, invoices, etc.
function buildClientPortalUrl(int $clientId): string {
    $scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
    $host   = $_SERVER['HTTP_HOST'];
    return $scheme . '://' . $host . '/Villaco/public_html/dashboard/templates/client_summary.html?clientId=' . urlencode($clientId);
}

$raw  = file_get_contents('php://input');
$data = json_decode($raw, true);

if (!is_array($data)) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Invalid JSON payload']);
    exit;
}

$client   = $data['client']   ?? null;
$contract = $data['contract'] ?? null;

if (!is_array($client) || !is_array($contract)) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Invalid client or contract data']);
    exit;
}

// Basic required fields
$surname       = trim($client['surname'] ?? '');
$firstName     = trim($client['firstName'] ?? '');
$fullName      = trim($client['fullName'] ?? '');
$phone         = trim($client['phone'] ?? '');
$areaId        = (int)($contract['areaId'] ?? 0);
$plotId        = (int)($contract['plotId'] ?? 0);
$originalPrice = $contract['originalPrice'] ?? null;
$finalPrice    = $contract['finalPrice'] ?? null;

if ($surname === '' || $firstName === '' || $phone === '' || $areaId <= 0 || $plotId <= 0) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Required fields missing.']);
    exit;
}

if ($originalPrice === null || !is_numeric($originalPrice) ||
    $finalPrice === null   || !is_numeric($finalPrice)) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Invalid price values.']);
    exit;
}

$discountCode      = $contract['discountCode']      ?? null;
$discountAmount    = $contract['discountAmount']    ?? 0;
$planType          = $contract['planType']          ?? 'Full Payment';
$planMonths        = $contract['planMonths']        ?? null;
$monthlyAmount     = $contract['monthlyAmount']     ?? null;
$clientCreatedAt   = $client['createdAt']           ?? null;
$contractCreatedAt = $contract['createdAt']         ?? null;

// Normalize date values coming from web (Y-m-d) to full datetime
$normalizeDateTime = function ($value): ?string {
    if ($value === null || $value === '') {
        return null;
    }

    $value = trim($value);

    if (strlen($value) === 10) {
        return $value . ' 00:00:00';
    }

    return $value;
};

$clientCreatedAt   = $normalizeDateTime($clientCreatedAt);
$contractCreatedAt = $normalizeDateTime($contractCreatedAt);

// Fallback to now ONLY if nothing was supplied
if ($clientCreatedAt === null) {
    $clientCreatedAt = date('Y-m-d H:i:s');
}
if ($contractCreatedAt === null) {
    $contractCreatedAt = $clientCreatedAt;
}

try {
    $pdo->beginTransaction();

    // 0) Ensure the plot exists
    $checkPlot = $pdo->prepare("
        SELECT Id, Status, ClientId, BuyerName
        FROM Plots
        WHERE Id = :Id
        LIMIT 1
    ");
    $checkPlot->execute([':Id' => $plotId]);
    $plotRow = $checkPlot->fetch(PDO::FETCH_ASSOC);
    if (!$plotRow) {
        throw new Exception("Selected plot does not exist (Id={$plotId}).");
    }

    // 1) Insert client
    $stmt = $pdo->prepare("
        INSERT INTO Clients (
            Surname, FirstName, OtherName, FullName,
            Gender, DateOfBirth, MaritalStatus, Nationality,
            StateOfOrigin, Lga, Address,
            Phone, AltPhone, Email,
            NokName, NokRelationship, NokPhone, NokAddress,
            CreatedAt
        ) VALUES (
            :Surname, :FirstName, :OtherName, :FullName,
            :Gender, :DateOfBirth, :MaritalStatus, :Nationality,
            :StateOfOrigin, :Lga, :Address,
            :Phone, :AltPhone, :Email,
            :NokName, :NokRelationship, :NokPhone, :NokAddress,
            :CreatedAt
        )
    ");

    $stmt->execute([
        ':Surname'         => $surname,
        ':FirstName'       => $firstName,
        ':OtherName'       => $client['otherName'] ?? null,
        ':FullName'        => $fullName !== '' ? $fullName : ($surname . ' ' . $firstName),
        ':Gender'          => $client['gender'] ?? null,
        ':DateOfBirth'     => !empty($client['dateOfBirth']) ? $client['dateOfBirth'] : null,
        ':MaritalStatus'   => $client['maritalStatus'] ?? null,
        ':Nationality'     => $client['nationality'] ?? null,
        ':StateOfOrigin'   => $client['stateOfOrigin'] ?? null,
        ':Lga'             => $client['lga'] ?? null,
        ':Address'         => $client['address'] ?? null,
        ':Phone'           => $phone,
        ':AltPhone'        => $client['altPhone'] ?? null,
        ':Email'           => $client['email'] ?? null,
        ':NokName'         => $client['nokName'] ?? null,
        ':NokRelationship' => $client['nokRelationship'] ?? null,
        ':NokPhone'        => $client['nokPhone'] ?? null,
        ':NokAddress'      => $client['nokAddress'] ?? null,
        ':CreatedAt'       => $clientCreatedAt,
    ]);

    $clientNumericId = (int)$pdo->lastInsertId();
    $clientCode      = sprintf('CL-%06d', $clientNumericId);

    $stmt = $pdo->prepare("
        UPDATE Clients
        SET ClientId = :ClientId
        WHERE Id = :Id
    ");
    $stmt->execute([
        ':ClientId' => $clientCode,
        ':Id'       => $clientNumericId,
    ]);

    // 2) Insert client contract
    $discountType  = null;
    $discountValue = null;

    if (!empty($discountCode) && $discountAmount > 0) {
        $discStmt = $pdo->prepare("
            SELECT Type, PercentageValue, AmountValue
            FROM Discounts
            WHERE Code = :Code
            LIMIT 1
        ");
        $discStmt->execute([':Code' => $discountCode]);
        $discRow = $discStmt->fetch(PDO::FETCH_ASSOC);

        if ($discRow) {
            $type = strtoupper(trim($discRow['Type'] ?? ''));

            if ($type === 'PERCENTAGE') {
                $perc = (float)($discRow['PercentageValue'] ?? 0);
                if ($perc > 0) {
                    $discountType  = 'PERCENTAGE';
                    $discountValue = $perc;
                }
            } elseif ($type === 'AMOUNT') {
                $amt = (float)($discRow['AmountValue'] ?? 0);
                if ($amt > 0) {
                    $discountType  = 'AMOUNT';
                    $discountValue = $amt;
                }
            }
        }
    }

    $stmt = $pdo->prepare("
        INSERT INTO ClientContracts (
            ClientId, PlotId,
            OriginalPrice, DiscountCode, DiscountType, DiscountValue, DiscountAmount,
            FinalPrice, PlanType, PlanMonths, MonthlyAmount,
            Status, CreatedAt
        ) VALUES (
            :ClientId, :PlotId,
            :OriginalPrice, :DiscountCode, :DiscountType, :DiscountValue, :DiscountAmount,
            :FinalPrice, :PlanType, :PlanMonths, :MonthlyAmount,
            'Active', :CreatedAt
        )
    ");

    $stmt->execute([
        ':ClientId'       => $clientNumericId,
        ':PlotId'         => $plotId,
        ':OriginalPrice'  => (float)$originalPrice,
        ':DiscountCode'   => $discountCode ?: null,
        ':DiscountType'   => $discountType,
        ':DiscountValue'  => $discountValue !== null ? (float)$discountValue : null,
        ':DiscountAmount' => (float)$discountAmount,
        ':FinalPrice'     => (float)$finalPrice,
        ':PlanType'       => $planType,
        ':PlanMonths'     => $planMonths !== null ? (int)$planMonths : null,
        ':MonthlyAmount'  => $monthlyAmount !== null ? (float)$monthlyAmount : null,
        ':CreatedAt'      => $contractCreatedAt,
    ]);

    $contractNumericId = (int)$pdo->lastInsertId();
    $contractCode      = sprintf('CT-%06d', $contractNumericId);

    $stmt = $pdo->prepare("
        UPDATE ClientContracts
        SET ContractId = :ContractId
        WHERE Id = :Id
    ");
    $stmt->execute([
        ':ContractId' => $contractCode,
        ':Id'         => $contractNumericId,
    ]);

    // 3) Update plot
    $debugBeforeStmt = $pdo->prepare("
        SELECT Id, Status, ClientId, BuyerName
        FROM Plots
        WHERE Id = :Id
        LIMIT 1
    ");
    $debugBeforeStmt->execute([':Id' => $plotId]);
    $before = $debugBeforeStmt->fetch(PDO::FETCH_ASSOC);

    $stmt = $pdo->prepare("
        UPDATE Plots
        SET Status   = 'Sold',
            ClientId = :ClientId,
            BuyerName = :BuyerName
        WHERE Id = :PlotId
    ");
    $stmt->execute([
        ':ClientId'  => $clientNumericId,
        ':BuyerName' => $fullName !== '' ? $fullName : ($surname . ' ' . $firstName),
        ':PlotId'    => $plotId,
    ]);

    $debugAfterStmt = $pdo->prepare("
        SELECT Id, Status, ClientId, BuyerName
        FROM Plots
        WHERE Id = :Id
        LIMIT 1
    ");
    $debugAfterStmt->execute([':Id' => $plotId]);
    $after = $debugAfterStmt->fetch(PDO::FETCH_ASSOC);

    file_put_contents(
        __DIR__ . '/add_client_plot_debug.log',
        date('Y-m-d H:i:s') .
        " plotId={$plotId} BEFORE=" . json_encode($before) .
        " AFTER=" . json_encode($after) . PHP_EOL,
        FILE_APPEND
    );

    if ($stmt->rowCount() === 0) {
        throw new Exception("No plot updated for Id={$plotId}");
    }

    // 4) Increment discount usage
    if (!empty($discountCode) && $discountAmount > 0) {
        $stmt = $pdo->prepare("
            UPDATE Discounts
            SET TimesUsed = IFNULL(TimesUsed, 0) + 1
            WHERE Code = :Code
        ");
        $stmt->execute([':Code' => $discountCode]);
    }

    $pdo->commit();

    // ======================= EMAIL SECTION =======================

    // Load plot + area info for email
    $plotStmt = $pdo->prepare("
        SELECT pl.Code AS PlotCode, a.Name AS AreaName
        FROM Plots pl
        INNER JOIN Areas a ON a.Id = pl.AreaId
        WHERE pl.Id = :plotId
        LIMIT 1
    ");
    $plotStmt->execute([':plotId' => $plotId]);
    $plotInfo = $plotStmt->fetch(PDO::FETCH_ASSOC) ?: ['PlotCode' => 'N/A', 'AreaName' => 'N/A'];

    $clientEmail = trim((string)($client['email'] ?? ''));
    $clientName  = $fullName !== '' ? $fullName : ($surname . ' ' . $firstName);

    // Discount description
    $discountLabel = 'No discount applied.';
    if (!empty($discountCode) && (float)$discountAmount > 0) {
        if ($discountType === 'PERCENTAGE' && $discountValue !== null) {
            $discountLabel = sprintf(
                'A %0.2f%% discount (%s) has been applied, saving you ₦%s.',
                (float)$discountValue,
                $discountCode,
                number_format((float)$discountAmount, 2, '.', ',')
            );
        } elseif ($discountType === 'AMOUNT' && $discountValue !== null) {
            $discountLabel = sprintf(
                'A flat discount of ₦%s (%s) has been applied.',
                number_format((float)$discountValue, 2, '.', ','),
                $discountCode
            );
        }
    }

    // Payment / due info
    $dueText = 'Payment is due according to your selected plan.';
    if ($planType === 'Full Payment') {
        $dueText = 'You selected Full Payment. Kindly ensure the full amount is settled as agreed with our office.';
    } elseif ($planType === 'Installment Plan' && !empty($planMonths) && !empty($monthlyAmount)) {
        $dueText = sprintf(
            'You selected an Installment Plan of %d months with a monthly payment of ₦%s.',
            (int)$planMonths,
            number_format((float)$monthlyAmount, 2, '.', ',')
        );
    }

    $portalUrl = buildClientPortalUrl($clientNumericId);

    $fmt = function (float $v): string {
        return '₦' . number_format($v, 2, '.', ',');
    };

    // Footer note for all emails
    $footerNote = '
        <p style="font-size:11px;color:#5d6a7c;margin-top:18px;border-top:1px solid #dbe4ef;padding-top:12px;line-height:1.7;">
            This is an automated email sent from <strong>Safe Step Properties Limited</strong>.<br>
            Sales, Investment &amp; Property Management<br>
            Suite 02, Jahi Mall, Valentine Nwabuaeze Crescent, Jahi, FCT Abuja.<br>
            Phone: +234 814 241 1113 / +234 704 646 6653<br>
            Email: info@safestepproperties.com
        </p>
    ';

    // 5a) Welcome email to client
    try {
        if ($clientEmail !== '') {
            $mail = createVillacoMailer();
            $mail->addAddress($clientEmail, $clientName);

            $mail->Subject = 'Welcome to Safe Step - Contract ' . $contractCode;

            $htmlBodyClient = '
                <div style="font-family:Poppins,Segoe UI,Tahoma,sans-serif;font-size:14px;color:#0b1b33;background:#f6f9fc;padding:24px;">
                    <div style="max-width:700px;margin:0 auto;background:#ffffff;border:1px solid #dbe4ef;border-radius:18px;overflow:hidden;">
                        <div style="padding:24px 24px 18px 24px;border-bottom:1px solid #dbe4ef;background:linear-gradient(135deg,#125db8,#3baa15);color:#ffffff;">
                            <div style="font-size:22px;font-weight:800;letter-spacing:0.14em;text-transform:uppercase;">
                                Safe Step Properties Limited
                            </div>
                            <div style="font-size:12px;margin-top:6px;font-weight:600;">
                                Sales, Investment &amp; Property Management
                            </div>
                            <div style="font-size:11px;margin-top:8px;opacity:0.95;line-height:1.6;">
                                Suite 02, Jahi Mall, Valentine Nwabuaeze Crescent, Jahi, FCT Abuja.<br>
                                Phone: +234 814 241 1113 / +234 704 646 6653<br>
                                Email: info@safestepproperties.com
                            </div>
                        </div>

                        <div style="padding:24px;">
                            <p style="margin:0 0 14px 0;">
                                Hello ' . htmlspecialchars($clientName) . ',
                            </p>

                            <p style="margin:0 0 16px 0;line-height:1.7;">
                                Welcome to <strong>Safe Step Properties Limited</strong>. Thank you for starting your property
                                purchase with us. Below are the details of your new contract.
                            </p>

                            <div style="font-size:11px;text-transform:uppercase;letter-spacing:0.14em;color:#125db8;font-weight:800;margin:0 0 10px 0;">
                                Contract Summary
                            </div>

                            <table cellpadding="8" cellspacing="0" style="width:100%;border-collapse:collapse;font-size:13px;border:1px solid #dbe4ef;border-radius:12px;overflow:hidden;">
                                <tr style="background:#eaf3ff;">
                                    <td style="color:#5d6a7c;font-weight:600;width:35%;">Client ID</td>
                                    <td style="font-weight:700;">' . htmlspecialchars($clientCode) . '</td>
                                </tr>
                                <tr>
                                    <td style="color:#5d6a7c;font-weight:600;">Contract ID</td>
                                    <td style="font-weight:700;">' . htmlspecialchars($contractCode) . '</td>
                                </tr>
                                <tr style="background:#eaf3ff;">
                                    <td style="color:#5d6a7c;font-weight:600;">Area</td>
                                    <td>' . htmlspecialchars($plotInfo['AreaName']) . '</td>
                                </tr>
                                <tr>
                                    <td style="color:#5d6a7c;font-weight:600;">Plot Code</td>
                                    <td style="font-weight:700;color:#125db8;">' . htmlspecialchars($plotInfo['PlotCode']) . '</td>
                                </tr>
                                <tr style="background:#eaf3ff;">
                                    <td style="color:#5d6a7c;font-weight:600;">Original Amount</td>
                                    <td style="font-weight:700;color:#125db8;">' . $fmt((float)$originalPrice) . '</td>
                                </tr>
                                <tr>
                                    <td style="color:#5d6a7c;font-weight:600;">Discount</td>
                                    <td>' . htmlspecialchars($discountLabel) . '</td>
                                </tr>
                                <tr style="background:#eaf3ff;">
                                    <td style="color:#5d6a7c;font-weight:600;">Final Amount</td>
                                    <td style="font-weight:700;color:#1f8f4e;">' . $fmt((float)$finalPrice) . '</td>
                                </tr>
                                <tr>
                                    <td style="color:#5d6a7c;font-weight:600;">Payment Plan</td>
                                    <td>' . htmlspecialchars($planType) . '</td>
                                </tr>
                                <tr style="background:#eaf3ff;">
                                    <td style="color:#5d6a7c;font-weight:600;">Installment Duration</td>
                                    <td>' . (!empty($planMonths) ? (int)$planMonths . ' months' : 'N/A') . '</td>
                                </tr>
                                <tr>
                                    <td style="color:#5d6a7c;font-weight:600;">Monthly Amount</td>
                                    <td>' . (!empty($monthlyAmount) ? $fmt((float)$monthlyAmount) : 'N/A') . '</td>
                                </tr>
                            </table>

                            <p style="margin:18px 0 10px 0;line-height:1.7;">
                                ' . htmlspecialchars($dueText) . '
                            </p>

                            <p style="margin:0 0 18px 0;line-height:1.7;">
                                You can track the status of your contract, follow your payments, and print invoices from your online client page:
                            </p>

                            <p style="margin:0 0 20px 0;">
                                <a href="' . htmlspecialchars($portalUrl) . '"
                                   style="display:inline-block;padding:11px 18px;background:#125db8;color:#ffffff;
                                          text-decoration:none;border-radius:10px;font-size:13px;font-weight:700;">
                                    View Contract Status Online
                                </a>
                            </p>

                            <p style="font-size:12px;color:#5d6a7c;line-height:1.7;margin:0;">
                                Thank you for your trust in Safe Step Properties Limited.
                            </p>

                            ' . $footerNote . '
                        </div>
                    </div>
                </div>
            ';

            $mail->Body    = $htmlBodyClient;
            $mail->AltBody = 'Welcome to Safe Step Properties Limited. Your contract ID is ' . $contractCode .
                '. You can view details at: ' . $portalUrl;

            $mail->send();
        }
    } catch (Exception $mailEx) {
        file_put_contents(
            __DIR__ . '/smtp_error.log',
            date('Y-m-d H:i:s') . ' CLIENT ' . $mailEx->getMessage() . PHP_EOL,
            FILE_APPEND
        );
    }

    // 5b) Notification email to Admin
    try {
        $mailAdmin = createVillacoMailer();
        $mailAdmin->addAddress('muntari.audullahi@gmail.com', 'Admin');

        $mailAdmin->Subject = 'New Client Registered - ' . $clientCode . ' (Safe Step)';

        $htmlBodyAdmin = '
            <div style="font-family:Poppins,Segoe UI,Tahoma,sans-serif;font-size:14px;color:#0b1b33;background:#f6f9fc;padding:24px;">
                <div style="max-width:700px;margin:0 auto;background:#ffffff;border:1px solid #dbe4ef;border-radius:18px;overflow:hidden;">
                    <div style="padding:24px 24px 18px 24px;border-bottom:1px solid #dbe4ef;background:linear-gradient(135deg,#125db8,#3baa15);color:#ffffff;">
                        <div style="font-size:22px;font-weight:800;letter-spacing:0.14em;text-transform:uppercase;">
                            Safe Step Properties Limited
                        </div>
                        <div style="font-size:12px;margin-top:6px;font-weight:600;">
                            New Client Notification
                        </div>
                        <div style="font-size:11px;margin-top:8px;opacity:0.95;line-height:1.6;">
                            Sales, Investment &amp; Property Management<br>
                            Suite 02, Jahi Mall, Valentine Nwabuaeze Crescent, Jahi, FCT Abuja.
                        </div>
                    </div>

                    <div style="padding:24px;">
                        <p style="margin:0 0 14px 0;">
                            Hello Admin,
                        </p>

                        <p style="margin:0 0 16px 0;line-height:1.7;">
                            A new client has just been added to the Safe Step Sales and Property Management System.
                            Below are the key details of the client and contract.
                        </p>

                        <div style="font-size:11px;text-transform:uppercase;letter-spacing:0.14em;color:#125db8;font-weight:800;margin:0 0 10px 0;">
                            Client Details
                        </div>

                        <table cellpadding="8" cellspacing="0" style="width:100%;border-collapse:collapse;font-size:13px;border:1px solid #dbe4ef;border-radius:12px;overflow:hidden;margin-bottom:18px;">
                            <tr style="background:#eaf3ff;">
                                <td style="color:#5d6a7c;font-weight:600;width:35%;">Client ID</td>
                                <td style="font-weight:700;">' . htmlspecialchars($clientCode) . '</td>
                            </tr>
                            <tr>
                                <td style="color:#5d6a7c;font-weight:600;">Name</td>
                                <td>' . htmlspecialchars($clientName) . '</td>
                            </tr>
                            <tr style="background:#eaf3ff;">
                                <td style="color:#5d6a7c;font-weight:600;">Phone</td>
                                <td>' . htmlspecialchars($phone) . '</td>
                            </tr>
                            <tr>
                                <td style="color:#5d6a7c;font-weight:600;">Email</td>
                                <td>' . htmlspecialchars($clientEmail) . '</td>
                            </tr>
                        </table>

                        <div style="font-size:11px;text-transform:uppercase;letter-spacing:0.14em;color:#125db8;font-weight:800;margin:0 0 10px 0;">
                            Contract Details
                        </div>

                        <table cellpadding="8" cellspacing="0" style="width:100%;border-collapse:collapse;font-size:13px;border:1px solid #dbe4ef;border-radius:12px;overflow:hidden;">
                            <tr style="background:#eaf3ff;">
                                <td style="color:#5d6a7c;font-weight:600;width:35%;">Contract ID</td>
                                <td style="font-weight:700;">' . htmlspecialchars($contractCode) . '</td>
                            </tr>
                            <tr>
                                <td style="color:#5d6a7c;font-weight:600;">Area</td>
                                <td>' . htmlspecialchars($plotInfo['AreaName']) . '</td>
                            </tr>
                            <tr style="background:#eaf3ff;">
                                <td style="color:#5d6a7c;font-weight:600;">Plot Code</td>
                                <td style="font-weight:700;color:#125db8;">' . htmlspecialchars($plotInfo['PlotCode']) . '</td>
                            </tr>
                            <tr>
                                <td style="color:#5d6a7c;font-weight:600;">Original Amount</td>
                                <td>' . $fmt((float)$originalPrice) . '</td>
                            </tr>
                            <tr style="background:#eaf3ff;">
                                <td style="color:#5d6a7c;font-weight:600;">Discount Info</td>
                                <td>' . htmlspecialchars($discountLabel) . '</td>
                            </tr>
                            <tr>
                                <td style="color:#5d6a7c;font-weight:600;">Final Amount</td>
                                <td style="font-weight:700;color:#1f8f4e;">' . $fmt((float)$finalPrice) . '</td>
                            </tr>
                            <tr style="background:#eaf3ff;">
                                <td style="color:#5d6a7c;font-weight:600;">Plan</td>
                                <td>' . htmlspecialchars($planType) . '</td>
                            </tr>
                            <tr>
                                <td style="color:#5d6a7c;font-weight:600;">Duration</td>
                                <td>' . (!empty($planMonths) ? (int)$planMonths . ' months' : 'N/A') . '</td>
                            </tr>
                            <tr style="background:#eaf3ff;">
                                <td style="color:#5d6a7c;font-weight:600;">Monthly Amount</td>
                                <td>' . (!empty($monthlyAmount) ? $fmt((float)$monthlyAmount) : 'N/A') . '</td>
                            </tr>
                        </table>

                        <p style="margin:18px 0 0 0;line-height:1.7;">
                            Admin link:
                            <a href="' . htmlspecialchars($portalUrl) . '" style="color:#125db8;text-decoration:none;font-weight:700;">
                                Open client summary
                            </a>
                        </p>

                        ' . $footerNote . '
                    </div>
                </div>
            </div>
        ';

        $mailAdmin->Body    = $htmlBodyAdmin;
        $mailAdmin->AltBody = 'New Safe Step client ' . $clientName . ' (' . $clientCode . ') with contract ' .
            $contractCode . '.';

        $mailAdmin->send();
    } catch (Exception $mailEx) {
        file_put_contents(
            __DIR__ . '/smtp_error.log',
            date('Y-m-d H:i:s') . ' ADMIN ' . $mailEx->getMessage() . PHP_EOL,
            FILE_APPEND
        );
    }

    // ======================= END EMAIL SECTION =======================

    echo json_encode([
        'success'      => true,
        'message'      => 'Client and plot saved successfully.',
        'clientId'     => $clientNumericId,
        'clientCode'   => $clientCode,
        'contractId'   => $contractNumericId,
        'contractCode' => $contractCode
    ]);
} catch (Exception $e) {
    if ($pdo->inTransaction()) {
        $pdo->rollBack();
    }

    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'Failed to save client and plot.',
        'details' => $e->getMessage()
    ]);
}
