<?php
// generate_receipt.php

// Increase memory limit for image processing
ini_set('memory_limit', '256M');

// Show errors for debugging; disable in production
ini_set('display_errors', 1);
error_reporting(E_ALL);

require_once '../includes/db.php';
require_once '../includes/functions.php';
require_once '../vendor/autoload.php';  // TCPDF

// Make sure user is logged in
redirectIfNotLoggedIn();

// ---------------------------------------------------------------------------
// Helper to mask an account number (e.g. "123400150015" → "**** **** 0015")
// ---------------------------------------------------------------------------
function maskAccountNumber($acctNumber)
{
    $acctNumber = trim($acctNumber);
    $len = strlen($acctNumber);
    if ($len <= 4) {
        return $acctNumber;
    }
    $last4 = substr($acctNumber, -4);
    return '**** **** ' . $last4;
}

// ---------------------------------------------------------------------------
// 1) Get transaction ID from query string
// ---------------------------------------------------------------------------
$txnId = $_GET['transaction_id'] ?? '';
if (!$txnId) {
    die('No transaction specified.');
}

// ---------------------------------------------------------------------------
// 2) Fetch transaction details from the DB (verifying it belongs to this user)
// ---------------------------------------------------------------------------
$userId = $_SESSION['user_id'];

$stmt = $pdo->prepare("
    SELECT 
        t.transaction_id,
        t.created_at,
        t.type,
        t.amount,
        t.description,
        
        -- The user's own account (for masking & new balance)
        me.account_number      AS account_number,
        me.balance             AS new_balance,
        
        -- Account holder's name
        u.full_name            AS full_name,

        -- Related account (if any)
        a.account_number       AS related_account_number,
        
        -- Loan due date if available (join with loans table)
        l.due_date             AS loan_due_date
    FROM transactions t
    JOIN accounts me       ON t.account_id = me.account_id
    JOIN users u           ON me.user_id = u.user_id
    LEFT JOIN accounts a   ON t.related_account_id = a.account_id
    LEFT JOIN loans l      ON t.type = 'approved_loan' AND l.amount = t.amount AND l.user_id = me.user_id
    WHERE t.transaction_id = ?
      AND me.user_id = ?
");
$stmt->execute([$txnId, $userId]);
$txn = $stmt->fetch();

if (!$txn) {
    die('Transaction not found or access denied.');
}

// ---------------------------------------------------------------------------
// 3) Derive values for display
// ---------------------------------------------------------------------------
$rawAmount = floatval($txn['amount'] ?? 0);
$isCredit = in_array($txn['type'], ['deposit', 'transfer_in', 'approved_loan', 'withdrawal_matured_investment']);
$signPrefix = $isCredit ? '+' : '-';
$absAmt = number_format(abs($rawAmount), 2);
$displayAmt = $signPrefix . '$ ' . $absAmt;

// Status is always “SUCCESS” for a completed transaction
$statusText = 'SUCCESS';

// Format date as "10 December, 2025 20:22"
$formattedDate = date('j F, Y H:i', strtotime($txn['created_at']));

// Mask the user's own account number
$maskedAcct = maskAccountNumber($txn['account_number']);

// Related account (or "—" if none)
$relatedAcct = $txn['related_account_number']
    ? $txn['related_account_number']
    : '—';

// Currency is always "PHP"
$currency = 'USD';

// Get transaction type display name
$typeDisplay = [
    'deposit' => 'Deposit',
    'withdrawal' => 'Withdrawal',
    'transfer_in' => 'Transfer In',
    'transfer_out' => 'Transfer Out',
    'investment' => 'Investment',
    'approved_loan' => 'Loan Approval',
    'withdrawal_matured_investment' => 'Matured Investment',
    'loanpayment' => 'Loan Payment'
];

$transactionType = $typeDisplay[$txn['type']] ?? strtoupper($txn['type']);

// ---------------------------------------------------------------------------
// 4) Create TCPDF document
// ---------------------------------------------------------------------------
$pdf = new \TCPDF('P', 'mm', 'A4', true, 'UTF-8', false);

// Document metadata
$pdf->SetCreator('Oakshire Finance');
$pdf->SetAuthor('Oakshire Finance');
$pdf->SetTitle('Transaction Receipt');
$pdf->SetSubject('Transaction Receipt');
$pdf->SetKeywords('Oakshire Finance, Receipt, Transaction');

// Disable default header/footer
$pdf->setPrintHeader(false);
$pdf->setPrintFooter(false);

// Margins: left=20mm, top=20mm, right=20mm
$pdf->SetMargins(20, 20, 20);

// Auto page breaks with bottom margin = 20mm
$pdf->SetAutoPageBreak(TRUE, 20);

// Add first page
$pdf->AddPage();

// ────────────────────────────────────────────────────────────────────────────
// A) COLORS & FONT SHORTCUTS
// ────────────────────────────────────────────────────────────────────────────
$primaryBlue = [10, 37, 64];    // #0a2540 - Navy
$accentBlue = [26, 77, 140];   // #1a4d8c
$successGreen = [46, 125, 50];   // #2e7d32
$errorRed = [220, 53, 69];   // #dc3545
$warningOrange = [243, 156, 18];  // #f39c12
$greyDark = [52, 58, 64];    // #343a40
$greyMedium = [108, 117, 125]; // #6c757d
$greyLight = [222, 226, 230]; // #dee2e6
$white = [255, 255, 255];

// All text will use DejaVu Sans (UTF-8 support)
$fontNormal = 'dejavusans';
$fontBold = 'dejavusans';
$fontItalic = 'dejavusans';

// ────────────────────────────────────────────────────────────────────────────
// B) HEADER: Logo + "Oakshire Finance" (left) - "Transaction Receipt" (right)
// ────────────────────────────────────────────────────────────────────────────

// B.1) Nexus Logo at (20mm, 20mm), width = 35mm
$logoFile = '../assets/images/LOGO-RECEIPT.jpg';
if (file_exists($logoFile)) {
    $pdf->Image($logoFile, 20, 20, 35, 0, '', '', 'T', false, 300);
} else {
    // Fallback text if logo not found
    $pdf->SetTextColor(...$primaryBlue);
    $pdf->SetFont($fontBold, 'B', 18);
    $pdf->SetXY(20, 28);
    $pdf->Cell(0, 10, 'Oakshire Finance', 0, 1, 'L', false);
}

// B.2) "Transaction Receipt" (14pt bold, accent blue) on the top-right
$pdf->SetTextColor(...$accentBlue);
$pdf->SetFont($fontBold, 'B', 14);
$pdf->SetXY(20, 25);
$pdf->Cell(0, 8, 'Transaction Receipt', 0, 1, 'R', false);

// B.3) Divider line after header
$pdf->SetDrawColor(...$greyLight);
$pdf->SetLineWidth(0.3);
$yHeaderDivider = $pdf->GetY() + 5;
$pdf->Line(20, $yHeaderDivider, 190, $yHeaderDivider);

// ────────────────────────────────────────────────────────────────────────────
// C) LARGE AMOUNT + STATUS + DATE
// ────────────────────────────────────────────────────────────────────────────

// Move down after divider
$pdf->SetY($yHeaderDivider + 10);

// C.1) Amount (36pt bold, colored based on transaction type)
if (in_array($txn['type'], ['withdrawal', 'transfer_out', 'investment'])) {
    $amountColor = $errorRed;
} else {
    $amountColor = $successGreen;
}

$pdf->SetTextColor(...$amountColor);
$pdf->SetFont($fontBold, 'B', 36);
$pdf->Cell(0, 15, $displayAmt, 0, 1, 'C', false);

// C.2) "SUCCESS" (16pt bold, primary blue), centered
$pdf->SetTextColor(...$primaryBlue);
$pdf->SetFont($fontBold, 'B', 16);
$pdf->Cell(0, 10, $statusText, 0, 1, 'C', false);

// C.3) Date (11pt normal, medium grey), centered
$pdf->SetTextColor(...$greyMedium);
$pdf->SetFont($fontNormal, '', 11);
$pdf->Cell(0, 8, $formattedDate, 0, 1, 'C', false);

// ────────────────────────────────────────────────────────────────────────────
// D) First Divider Line (0.3pt thick, light grey)
// ────────────────────────────────────────────────────────────────────────────
$pdf->Ln(5);
$pdf->SetDrawColor(...$greyLight);
$pdf->SetLineWidth(0.3);
$yDivider1 = $pdf->GetY();
$pdf->Line(20, $yDivider1, 190, $yDivider1);
$pdf->Ln(10);

// ────────────────────────────────────────────────────────────────────────────
// E) TRANSACTION DETAILS TABLE
// ────────────────────────────────────────────────────────────────────────────

// E.1) Prepare all rows as [label, value]
$rows = [
    ['Transaction ID', $txn['transaction_id']],
    ['Account Number', $maskedAcct],
    ['Account Holder', $txn['full_name']],
    ['Transaction Type', $transactionType],
    ['Currency', $currency],
    ['New Account Balance', '$ ' . number_format($txn['new_balance'], 2)],
    ['Related Account', $relatedAcct],
];

// E.2) Layout constants
$xLabel = 20;   // left margin for label
$wLabel = 65;   // width for label cell
$xColon = $xLabel + $wLabel + 2;
$wColon = 5;    // width for colon
$xValue = $xColon + $wColon + 2;
$wValue = 190 - $xValue;
$rowHeight = 9;    // each row is 9mm tall

// E.3) Loop through rows
foreach ($rows as $row) {
    list($label, $value) = $row;

    // Label (10pt normal, medium grey)
    $pdf->SetTextColor(...$greyMedium);
    $pdf->SetFont($fontNormal, '', 10);
    $pdf->SetXY($xLabel, $pdf->GetY());
    $pdf->Cell($wLabel, $rowHeight, $label, 0, 0, 'L', false);

    // Colon ":" (10pt normal, medium grey)
    $pdf->SetTextColor(...$greyMedium);
    $pdf->SetFont($fontNormal, '', 10);
    $pdf->SetXY($xColon, $pdf->GetY());
    $pdf->Cell($wColon, $rowHeight, ':', 0, 0, 'L', false);

    // Value (10pt bold, dark grey), right-aligned
    $pdf->SetTextColor(...$greyDark);
    $pdf->SetFont($fontBold, 'B', 10);
    $pdf->SetXY($xValue, $pdf->GetY());
    $pdf->Cell($wValue, $rowHeight, $value, 0, 1, 'R', false);
}

// ────────────────────────────────────────────────────────────────────────────
// F) Second Divider after details
// ────────────────────────────────────────────────────────────────────────────
$pdf->Ln(2);
$pdf->SetDrawColor(...$greyLight);
$pdf->SetLineWidth(0.3);
$yDivider2 = $pdf->GetY();
$pdf->Line(20, $yDivider2, 190, $yDivider2);
$pdf->Ln(8);

// ────────────────────────────────────────────────────────────────────────────
// G) DESCRIPTION ROW (Single row)
// ────────────────────────────────────────────────────────────────────────────

// G.1) Label = "Description"
$pdf->SetTextColor(...$greyMedium);
$pdf->SetFont($fontNormal, '', 10);
$pdf->SetXY($xLabel, $pdf->GetY());
$pdf->Cell($wLabel, $rowHeight, 'Description', 0, 0, 'L', false);

// G.2) Colon ":"
$pdf->SetTextColor(...$greyMedium);
$pdf->SetFont($fontNormal, '', 10);
$pdf->SetXY($xColon, $pdf->GetY());
$pdf->Cell($wColon, $rowHeight, ':', 0, 0, 'L', false);

$descText = trim($txn['description'] ?? '');
if ($descText === '') {
    $descText = '—';
}
$pdf->SetTextColor(...$greyDark);
$pdf->SetFont($fontBold, 'B', 10);
$pdf->SetXY($xValue, $pdf->GetY());
$pdf->Cell($wValue, $rowHeight, $descText, 0, 1, 'R', false);

// Add Due Date row for approved loans
if ($txn['type'] === 'approved_loan' && !empty($txn['loan_due_date'])) {
    $pdf->SetTextColor(...$greyMedium);
    $pdf->SetFont($fontNormal, '', 10);
    $pdf->SetXY($xLabel, $pdf->GetY());
    $pdf->Cell($wLabel, $rowHeight, 'Due Date', 0, 0, 'L', false);

    $pdf->SetTextColor(...$greyMedium);
    $pdf->SetFont($fontNormal, '', 10);
    $pdf->SetXY($xColon, $pdf->GetY());
    $pdf->Cell($wColon, $rowHeight, ':', 0, 0, 'L', false);

    $dueDateFormatted = date('M j, Y', strtotime($txn['loan_due_date']));
    $pdf->SetTextColor(...$greyDark);
    $pdf->SetFont($fontBold, 'B', 10);
    $pdf->SetXY($xValue, $pdf->GetY());
    $pdf->Cell($wValue, $rowHeight, $dueDateFormatted, 0, 1, 'R', false);
}

// ────────────────────────────────────────────────────────────────────────────
// H) Third Divider after description
// ────────────────────────────────────────────────────────────────────────────
$pdf->Ln(2);
$pdf->SetDrawColor(...$greyLight);
$pdf->SetLineWidth(0.3);
$yDivider3 = $pdf->GetY();
$pdf->Line(20, $yDivider3, 190, $yDivider3);
$pdf->Ln(12);

// ────────────────────────────────────────────────────────────────────────────
// I) FOOTER TEXT
// ────────────────────────────────────────────────────────────────────────────

// I.1) "This is a system-generated receipt. No signature is required."
$pdf->SetTextColor(...$greyMedium);
$pdf->SetFont($fontNormal, '', 10);
$pdf->MultiCell(
    0,
    6,
    "This is a system-generated receipt.\nNo signature is required.",
    0,
    'C',
    false,
    1
);
$pdf->Ln(4);

// I.2) "Support" (11pt normal, primary blue), centered
$pdf->SetTextColor(...$primaryBlue);
$pdf->SetFont($fontNormal, '', 11);
$pdf->Cell(0, 6, 'Support', 0, 1, 'C', false);

// I.3) Support email (11pt bold, accent blue), centered
$pdf->SetTextColor(...$accentBlue);
$pdf->SetFont($fontBold, 'B', 11);
$pdf->Cell(0, 6, 'support@oakshirefinance.com', 0, 1, 'C', false);

// I.4) Support phone (10pt normal, medium grey), centered
$pdf->SetTextColor(...$greyMedium);
$pdf->SetFont($fontNormal, '', 10);
$pdf->Cell(0, 6, '1-800-NEXUS-01', 0, 1, 'C', false);
$pdf->Ln(6);

// ────────────────────────────────────────────────────────────────────────────
// J) DOTTED GREY LINE (0.3pt, dash pattern 2/2 for better visibility)
// ────────────────────────────────────────────────────────────────────────────

// J.1) Set dash pattern for dotted line (2mm on, 2mm off)
$pdf->SetDrawColor(...$greyLight);
$pdf->SetLineWidth(0.3);
$pdf->SetLineStyle(['width' => 0.3, 'dash' => '2,2', 'color' => $greyLight]);

// J.2) Draw the line from x=20 to x=190 at current Y
$yDotted = $pdf->GetY();
$pdf->Line(20, $yDotted, 190, $yDotted);

// J.3) Reset to solid lines
$pdf->SetLineStyle(['width' => 0.3, 'dash' => 0, 'color' => $greyLight]);
$pdf->Ln(10);

// ────────────────────────────────────────────────────────────────────────────
// K) PROMO / DISCLAIMER PARAGRAPH (9pt normal, light grey), centered
// ────────────────────────────────────────────────────────────────────────────
$pdf->SetTextColor(...$greyMedium);
$pdf->SetFont($fontNormal, '', 9);

$promoText =
    "Enjoy a better life with Oakshire Finance. Get free transfers, withdrawals, bill payments, instant\n" .
    "loans, and competitive annual interest on your savings. Oakshire Finance is licensed by the\n" .
    "Bangko Sentral ng Pilipinas and insured by the PDIC.";

$pdf->MultiCell(
    0,
    5,
    $promoText,
    0,
    'C',
    false
);

// ────────────────────────────────────────────────────────────────────────────
// L) BOTTOM LINE WITH BRANCH INFO
// ────────────────────────────────────────────────────────────────────────────
$pdf->Ln(5);
$pdf->SetDrawColor(...$greyLight);
$pdf->SetLineWidth(0.3);
$yBottomLine = $pdf->GetY();
$pdf->Line(20, $yBottomLine, 190, $yBottomLine);
$pdf->Ln(5);

$pdf->SetTextColor(...$greyMedium);
$pdf->SetFont($fontNormal, '', 8);
$pdf->Cell(0, 5, 'Oakshire Finance - Main Branch | 123 Financial District, Makati City | www.oakshirefinance.com', 0, 1, 'C', false);

// ────────────────────────────────────────────────────────────────────────────
// M) OUTPUT THE PDF
// ────────────────────────────────────────────────────────────────────────────
$filename = "receipt_{$txn['transaction_id']}.pdf";
$pdf->Output($filename, 'I');
exit();