<?php
// api/send_payment_receipt_email.php?paymentId=10
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;
}

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;

$paymentId = isset($_GET['paymentId']) ? (int)$_GET['paymentId'] : 0;
if ($paymentId <= 0) {
    http_response_code(400);
    echo json_encode(['status' => 'error', 'message' => 'Missing or invalid paymentId']);
    exit;
}

$mail = null;

try {
    // 1) Load payment + contract + client + plot + area
    $sql = "
        SELECT
            p.Id                  AS PaymentId,
            p.ContractId          AS ContractId,
            p.PaymentDate,
            p.Amount,
            p.Method,
            p.Reference,
            p.Notes,
            p.InvoiceNumber,

            c.Id                  AS ClientId,
            c.ClientId            AS ClientCode,
            c.FullName            AS ClientName,
            c.Phone               AS ClientPhone,
            c.Email               AS ClientEmail,

            cc.FinalPrice         AS ContractFinalPrice,

            pl.Code               AS PlotCode,
            pl.Status             AS PlotStatus,
            a.Name                AS AreaName
        FROM ClientPayments p
        INNER JOIN ClientContracts cc ON cc.Id = p.ContractId
        INNER JOIN Clients c          ON c.Id  = cc.ClientId
        INNER JOIN Plots pl           ON pl.Id = cc.PlotId
        INNER JOIN Areas a            ON a.Id  = pl.AreaId
        WHERE p.Id = :paymentId
        LIMIT 1
    ";

    $stmt = $pdo->prepare($sql);
    $stmt->execute([':paymentId' => $paymentId]);
    $row = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$row) {
        http_response_code(404);
        echo json_encode(['status' => 'error', 'message' => 'Payment not found']);
        exit;
    }

    // 2) Basic fields
    $clientEmail = trim((string)$row['ClientEmail']);
    if ($clientEmail === '') {
        http_response_code(400);
        echo json_encode(['status' => 'error', 'message' => 'Client has no email address on record.']);
        exit;
    }

    $contractId     = (int)$row['ContractId'];
    $contractValue  = (float)$row['ContractFinalPrice'];
    $amountPaid     = (float)$row['Amount'];
    $paymentDateRaw = $row['PaymentDate'];
    $paymentDate    = date('d M Y', strtotime($paymentDateRaw));

    $receiptNumber  = $row['InvoiceNumber'] ?: sprintf(
        'REC-%s-%04d',
        date('Ymd', strtotime($paymentDateRaw)),
        (int)$row['PaymentId']
    );
    $clientCode   = $row['ClientCode'] ?: sprintf('CL-%06d', (int)$row['ClientId']);
    $contractCode = sprintf('CT-%06d', $contractId);

    // 3) Totals for outstanding
    $sumAllStmt = $pdo->prepare("
        SELECT IFNULL(SUM(Amount), 0) AS TotalPaidAll
        FROM ClientPayments
        WHERE ContractId = :contractId
          AND (IsDeleted IS NULL OR IsDeleted = 0)
    ");
    $sumAllStmt->execute([':contractId' => $contractId]);
    $allRow = $sumAllStmt->fetch(PDO::FETCH_ASSOC);
    $totalPaidAll = (float)($allRow['TotalPaidAll'] ?? 0);
    $outstanding  = max($contractValue - $totalPaidAll, 0);

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

    // 4) Build receipt URL
    $scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
    $host   = $_SERVER['HTTP_HOST'];
    $receiptUrl = $scheme . '://' . $host . '/dashboard/templates/receipt.html?paymentId=' . urlencode($paymentId);

    $clientName = $row['ClientName'];
    $areaName   = $row['AreaName'];
    $plotCode   = $row['PlotCode'];

    // 5) Safe Step branded HTML
    $htmlBody = '
        <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;">
                        Dear ' . htmlspecialchars($clientName) . ',
                    </p>

                    <p style="margin:0 0 14px 0;line-height:1.7;">
                        This email confirms receipt of your payment for your property with
                        <strong>Safe Step Properties Limited</strong>.
                    </p>

                    <div style="font-size:11px;text-transform:uppercase;letter-spacing:0.14em;color:#125db8;font-weight:800;margin:0 0 10px 0;">
                        Receipt 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%;">Receipt No</td>
                            <td style="font-weight:700;">' . htmlspecialchars($receiptNumber) . '</td>
                        </tr>
                        <tr>
                            <td style="color:#5d6a7c;font-weight:600;">Client</td>
                            <td style="font-weight:700;">' . htmlspecialchars($clientName) . ' (' . htmlspecialchars($clientCode) . ')</td>
                        </tr>
                        <tr style="background:#eaf3ff;">
                            <td style="color:#5d6a7c;font-weight:600;">Contract</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;">Payment Date</td>
                            <td>' . htmlspecialchars($paymentDate) . '</td>
                        </tr>
                        <tr style="background:#eaf3ff;">
                            <td style="color:#5d6a7c;font-weight:600;">Amount Paid</td>
                            <td style="font-weight:700;color:#1f8f4e;">' . $formatMoney($amountPaid) . '</td>
                        </tr>
                        <tr>
                            <td style="color:#5d6a7c;font-weight:600;">Total Contract Value</td>
                            <td style="font-weight:700;color:#125db8;">' . $formatMoney($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;">' . $formatMoney($totalPaidAll) . '</td>
                        </tr>
                        <tr>
                            <td style="color:#5d6a7c;font-weight:600;">Outstanding Balance</td>
                            <td style="font-weight:700;color:#c0392b;">' . $formatMoney($outstanding) . '</td>
                        </tr>
                    </table>

                    <p style="margin:18px 0 10px 0;line-height:1.7;">
                        You can view and print the full receipt online 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;margin:0;">
                        Thank you for your trust in Safe Step Properties Limited.
                    </p>

                    <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>
                </div>
            </div>
        </div>
    ';

    // 6) Configure PHPMailer with Gmail App Password
    $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';

    // Debug logging
    $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->addAddress($clientEmail, $clientName);

    $mail->Subject = 'Payment Receipt - ' . $receiptNumber;
    $mail->isHTML(true);
    $mail->Body    = $htmlBody;
    $mail->AltBody = 'Your payment receipt is available at: ' . $receiptUrl;

    $mail->send();

    echo json_encode(['status' => 'ok', 'message' => 'Email sent successfully']);
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'status'  => 'error',
        'message' => 'Mailer error: ' . ($mail ? $mail->ErrorInfo : $e->getMessage())
    ]);
}
