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

header('Content-Type: application/json; charset=UTF-8');
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';

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;

/**
 * PHPMailer configured for Safe Step using muntari.audullahi@gmail.com
 */
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   = 'B@kori2263';
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
    $mail->Port       = 587;
    $mail->CharSet    = 'UTF-8';

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

    return $mail;
}

/**
 * Build client portal URL for Safe Step client summary
 * Adjust path if needed for your actual deployment.
 */
function buildClientPortalUrl(int $clientId): string {
    $scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
    $host   = $_SERVER['HTTP_HOST'];
    // Example: http://localhost/Villaco/public_html/dashboard/templates/client_summary.html?clientId=123
    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;
}

// Required minimal fields from desktop app
$clientIdNum   = (int)($client['clientIdNumeric'] ?? 0);
$clientCode    = trim((string)($client['clientCode'] ?? ''));
$clientName    = trim((string)($client['fullName'] ?? ''));
$clientEmail   = trim((string)($client['email'] ?? ''));
$clientPhone   = trim((string)($client['phone'] ?? ''));

$contractIdNum = (int)($contract['contractIdNumeric'] ?? 0);
$contractCode  = trim((string)($contract['contractCode'] ?? ''));
$areaName      = trim((string)($contract['areaName'] ?? ''));
$plotCode      = trim((string)($contract['plotCode'] ?? ''));
$originalPrice = (float)($contract['originalPrice'] ?? 0);
$finalPrice    = (float)($contract['finalPrice'] ?? 0);
$discountCode  = trim((string)($contract['discountCode'] ?? ''));
$discountType  = trim((string)($contract['discountType'] ?? ''));
$discountValue = isset($contract['discountValue']) ? (float)$contract['discountValue'] : null;
$discountAmount = (float)($contract['discountAmount'] ?? 0);
$planType      = trim((string)($contract['planType'] ?? 'Full Payment'));
$planMonths    = (int)($contract['planMonths'] ?? 0);
$monthlyAmount = (float)($contract['monthlyAmount'] ?? 0);

if ($clientIdNum <= 0 || $clientCode === '' || $contractCode === '') {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Missing required IDs.']);
    exit;
}

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

// Due text
$dueText = 'Payment is due according to your selected plan.';
if ($planType === 'Full Payment') {
    $dueText = 'You selected Full Payment. You may pay the full contract amount at once or in parts, but kindly ensure the total is settled as agreed with our office.';
} elseif ($planType === 'Installment Plan' && $planMonths > 0 && $monthlyAmount > 0) {
    $monthlyFormatted = number_format($monthlyAmount, 2, '.', ',');
    $nextDueDate      = date('d M Y', strtotime('+1 month'));
    $dueText = sprintf(
        'You selected an Installment Plan of %d months. Your suggested monthly payment is ₦%s, but you may pay any amount to Safe Step Properties at any time and it will be recorded. Your next payment is due on %s.',
        $planMonths,
        $monthlyFormatted,
        $nextDueDate
    );
}

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

$portalUrl = buildClientPortalUrl($clientIdNum);

// Footer note with Safe Step branding
$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>
';

$errors = [];

// 1) Client email
if ($clientEmail !== '') {
    try {
        $mail = createVillacoMailer();
        $mail->addAddress($clientEmail, $clientName ?: $clientCode);
        $mail->Subject = 'Welcome to Safe Step - Contract ' . $contractCode;

        $body = '
            <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:12px 0;">
                            Hello ' . htmlspecialchars($clientName ?: $clientCode) . ',
                        </p>
                        <p style="margin:0 0 12px 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:16px 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($areaName) . '</td>
                            </tr>
                            <tr>
                                <td style="color:#5d6a7c;font-weight:600;">Plot Code:</td>
                                <td style="font-weight:700;color:#125db8;">' . htmlspecialchars($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($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($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>' . ($planMonths > 0 ? $planMonths . ' months' : 'N/A') . '</td>
                            </tr>
                            <tr>
                                <td style="color:#5d6a7c;font-weight:600;">Monthly Amount:</td>
                                <td>' . ($planMonths > 0 ? $fmt($monthlyAmount) : 'N/A') . '</td>
                            </tr>
                        </table>

                        <p style="margin:16px 0 8px 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 18px 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;">
                            Thank you for choosing Safe Step Properties Limited. We look forward to completing this journey with you.
                        </p>

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

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

        $mail->send();
    } catch (Exception $ex) {
        $errors[] = 'Client email error: ' . $ex->getMessage();
    }
}

// 2) Internal notification
try {
    $mailAdmin = createVillacoMailer();
    $mailAdmin->addAddress('muntari.audullahi@gmail.com', 'Admin');

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

    $adminBody = '
        <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:12px 0;">
                        Hello Admin,
                    </p>
                    <p style="margin:0 0 12px 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:16px 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 ?: $clientCode) . '</td>
                        </tr>
                        <tr style="background:#eaf3ff;">
                            <td style="color:#5d6a7c;font-weight:600;">Phone:</td>
                            <td>' . htmlspecialchars($clientPhone) . '</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:16px 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($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($plotCode) . '</td>
                        </tr>
                        <tr>
                            <td style="color:#5d6a7c;font-weight:600;">Original Amount:</td>
                            <td>' . $fmt($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($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>' . ($planMonths > 0 ? $planMonths . ' months' : 'N/A') . '</td>
                        </tr>
                        <tr style="background:#eaf3ff;">
                            <td style="color:#5d6a7c;font-weight:600;">Monthly Amount:</td>
                            <td>' . ($planMonths > 0 ? $fmt($monthlyAmount) : 'N/A') . '</td>
                        </tr>
                    </table>

                    <p style="margin:16px 0 8px 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    = $adminBody;
    $mailAdmin->AltBody = 'New Safe Step client ' . ($clientName ?: $clientCode) . ' (' . $clientCode . ') with contract ' .
        $contractCode . '.';

    $mailAdmin->send();
} catch (Exception $ex) {
    $errors[] = 'Admin email error: ' . $ex->getMessage();
}

echo json_encode([
    'success' => empty($errors),
    'errors'  => $errors
]);
