<?php
// api/send_payment_recorded_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;

function createSafeStepMailer(): 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';

    $mail->SMTPDebug = 0;
    $mail->Debugoutput = function ($str, $level) {
        file_put_contents(
            __DIR__ . '/smtp_debug.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;
}

function buildReceiptUrl(int $paymentId): string {
    $scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
    $host   = $_SERVER['HTTP_HOST'];
    return $scheme . '://' . $host . '/dashboard/templates/receipt.html?paymentId=' . urlencode($paymentId);
}

$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;
}

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

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

// Payment fields
$paymentId      = (int)($payment['paymentId'] ?? 0);
$invoiceNumber  = (string)($payment['invoiceNumber'] ?? '');
$amountPaid     = (float)($payment['amountPaid'] ?? 0);
$paymentDateStr = (string)($payment['paymentDate'] ?? '');
$method         = (string)($payment['method'] ?? '');
$reference      = (string)($payment['reference'] ?? '');

// Client fields
$clientCode  = (string)($client['clientCode'] ?? '');
$clientName  = (string)($client['fullName'] ?? '');
$clientEmail = (string)($client['email'] ?? '');
$clientPhone = (string)($client['phone'] ?? '');

// Contract fields
$contractCode   = (string)($contract['contractCode'] ?? '');
$areaName       = (string)($contract['areaName'] ?? '');
$plotCode       = (string)($contract['plotCode'] ?? '');
$contractValue  = (float)($contract['finalPrice'] ?? 0);
$totalPaidAfter = (float)($contract['totalPaidAfter'] ?? 0);
$outstanding    = (float)($contract['outstanding'] ?? 0);

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

$receiptUrl = buildReceiptUrl($paymentId);

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

$paymentDateNice = $paymentDateStr ? date('d M Y', strtotime($paymentDateStr)) : 'N/A';

$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 = createSafeStepMailer();
        $mail->addAddress($clientEmail, $clientName ?: $clientCode);
        $mail->Subject = 'Payment Recorded - 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;">
                            Safe Step Properties Limited has just recorded your payment for your contract. Thank you for your payment.
                        </p>

                        <div style="font-size:11px;text-transform:uppercase;letter-spacing:0.14em;color:#125db8;font-weight:800;margin:16px 0 10px 0;">
                            Contract &amp; Property
                        </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>
                        </table>

                        <div style="font-size:11px;text-transform:uppercase;letter-spacing:0.14em;color:#125db8;font-weight:800;margin:16px 0 10px 0;">
                            Payment 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%;">Invoice No</td>
                                <td style="font-weight:700;">' . htmlspecialchars($invoiceNumber) . '</td>
                            </tr>
                            <tr>
                                <td style="color:#5d6a7c;font-weight:600;">Payment Date</td>
                                <td>' . htmlspecialchars($paymentDateNice) . '</td>
                            </tr>
                            <tr style="background:#eaf3ff;">
                                <td style="color:#5d6a7c;font-weight:600;">Payment Method</td>
                                <td>' . htmlspecialchars($method) . '</td>
                            </tr>
                            <tr>
                                <td style="color:#5d6a7c;font-weight:600;">Reference</td>
                                <td>' . htmlspecialchars($reference) . '</td>
                            </tr>
                            <tr style="background:#eaf3ff;">
                                <td style="color:#5d6a7c;font-weight:600;">Contract Value</td>
                                <td style="font-weight:700;color:#125db8;">' . $fmt($contractValue) . '</td>
                            </tr>
                            <tr>
                                <td style="color:#5d6a7c;font-weight:600;">Amount Paid Now</td>
                                <td style="font-weight:700;color:#1f8f4e;">' . $fmt($amountPaid) . '</td>
                            </tr>
                            <tr style="background:#eaf3ff;">
                                <td style="color:#5d6a7c;font-weight:600;">Total Paid So Far</td>
                                <td style="font-weight:700;color:#1f8f4e;">' . $fmt($totalPaidAfter) . '</td>
                            </tr>
                            <tr>
                                <td style="color:#5d6a7c;font-weight:600;">Outstanding Balance</td>
                                <td style="font-weight:700;color:#c0392b;">' . $fmt($outstanding) . '</td>
                            </tr>
                        </table>

                        <p style="margin:16px 0 8px 0;line-height:1.7;">
                            You can view and print your detailed receipt using the link below:
                        </p>
                        <p style="margin:0 0 18px 0;">
                            <a href="' . htmlspecialchars($receiptUrl) . '"
                               style="display:inline-block;padding:11px 18px;background:#125db8;color:#ffffff;
                                      text-decoration:none;border-radius:10px;font-size:13px;font-weight:700;">
                                View Receipt Online
                            </a>
                        </p>

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

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

        $mail->Body    = $body;
        $mail->AltBody = 'Your payment has been recorded. Receipt: ' . $receiptUrl;

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

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

    $mailAdmin->Subject = 'Payment Recorded - ' . $clientCode . ' / ' . $contractCode;

    $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;">
                        Client Payment 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 client payment has just been recorded in the Safe Step Sales and Property Management System.
                    </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;">
                        <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 &amp; Payment
                    </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;">Invoice No</td>
                            <td>' . htmlspecialchars($invoiceNumber) . '</td>
                        </tr>
                        <tr style="background:#eaf3ff;">
                            <td style="color:#5d6a7c;font-weight:600;">Payment Date</td>
                            <td>' . htmlspecialchars($paymentDateNice) . '</td>
                        </tr>
                        <tr>
                            <td style="color:#5d6a7c;font-weight:600;">Payment Method</td>
                            <td>' . htmlspecialchars($method) . '</td>
                        </tr>
                        <tr style="background:#eaf3ff;">
                            <td style="color:#5d6a7c;font-weight:600;">Amount Paid Now</td>
                            <td style="font-weight:700;color:#1f8f4e;">' . $fmt($amountPaid) . '</td>
                        </tr>
                        <tr>
                            <td style="color:#5d6a7c;font-weight:600;">Contract Value</td>
                            <td style="font-weight:700;color:#125db8;">' . $fmt($contractValue) . '</td>
                        </tr>
                        <tr style="background:#eaf3ff;">
                            <td style="color:#5d6a7c;font-weight:600;">Total Paid So Far</td>
                            <td style="font-weight:700;color:#1f8f4e;">' . $fmt($totalPaidAfter) . '</td>
                        </tr>
                        <tr>
                            <td style="color:#5d6a7c;font-weight:600;">Outstanding Balance</td>
                            <td style="font-weight:700;color:#c0392b;">' . $fmt($outstanding) . '</td>
                        </tr>
                    </table>

                    <p style="margin:16px 0 8px 0;line-height:1.7;">
                        Receipt link:
                        <a href="' . htmlspecialchars($receiptUrl) . '" style="color:#125db8;text-decoration:none;font-weight:700;">
                            Open payment receipt
                        </a>
                    </p>

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

    $mailAdmin->Body    = $adminBody;
    $mailAdmin->AltBody = 'Payment recorded for ' . ($clientName ?: $clientCode) .
        ' on contract ' . $contractCode . '. Amount: ' . $fmt($amountPaid) .
        '. Outstanding: ' . $fmt($outstanding) . '.';

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

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