<?php

require('fpdf/fpdf.php');

// ==========================
// 1. GET INPUT DATA
// ==========================

$input = $_POST;

if (empty($input)) {
    $json = file_get_contents("php://input");
    $input = json_decode($json, true) ?? [];
}

// ==========================
// 2. LOG DATA
// ==========================

if (!file_exists('logs')) {
    mkdir('logs', 0777, true);
}

file_put_contents(
    'logs/requests.txt',
    date('Y-m-d H:i:s') . " | " . json_encode($input) . PHP_EOL,
    FILE_APPEND
);

// ==========================
// 3. MAP DATA
// ==========================

$receiptId   = $input['receiptId'] ?? '';
$invoiceNo   = $input['adviceRefNumber'] ?? '';
$platform    = $input['platformName'] ?? '';
$institution = $input['institutionName'] ?? '';
$customer    = $input['customerName'] ?? '';
$nic         = $input['customerNIC'] ?? '';
$merchant    = $input['merchantName'] ?? '';

$saleDate    = $input['saleDate'] ?? '';
$paymentDate = $input['paymentDate'] ?? '';
$paymentTime = $input['paymentTime'] ?? '';

$installmentNo   = $input['installmentNumber'] ?? '';
$totalInst       = $input['totalInstallments'] ?? '';
$installmentAmt  = $input['installmentAmount'] ?? '';
$remaining       = $input['remainingOutstandingBalance'] ?? '';

$paymentMethod   = $input['paymentMethod'] ?? '';
$status          = $input['status'] ?? '';
$planName        = $input['planName'] ?? '';
$footer          = $input['systemFooter'] ?? '';

// ==========================
// FORMAT
// ==========================

function fdate($d) {
    return $d ? date('M d, Y H:i', strtotime($d)) : '';
}

$saleDate    = fdate($saleDate);
$paymentDate = fdate($paymentDate);

// ==========================
// PDF START
// ==========================

$pdf = new FPDF();
$pdf->AddPage();

// ===== COLORS =====
$blue = [41, 128, 185];

// ===== LOGO =====
$pdf->Image('https://hexdive.com/pdf/logo.png', 150, 10, 40);

// ===== HEADER =====
$pdf->SetFont('Arial','B',18);
$pdf->SetTextColor(0,0,0);
$pdf->Cell(0,10,$institution,0,1);

$pdf->SetFont('Arial','',10);
$pdf->SetTextColor(100,100,100);
$pdf->Cell(0,6,'Payment Receipt - '.$platform,0,1);

$pdf->Ln(5);

// ===== LINE =====
$pdf->SetDrawColor($blue[0], $blue[1], $blue[2]);
$pdf->SetLineWidth(0.8);
$pdf->Line(10, 35, 200, 35);

$pdf->Ln(8);

// ===== CUSTOMER / MERCHANT =====
$pdf->SetFont('Arial','B',11);
$pdf->SetTextColor(0,0,0);

$pdf->Cell(100,6,'Billed To',0,0);
$pdf->Cell(0,6,'Merchant',0,1);

$pdf->SetFont('Arial','',11);

$pdf->Cell(100,6,$customer,0,0);
$pdf->Cell(0,6,$merchant,0,1);

$pdf->SetFont('Arial','',10);
$pdf->SetTextColor(120,120,120);
$pdf->Cell(100,6,'NIC: '.$nic,0,1);

$pdf->Ln(6);

// ===== META =====
$pdf->SetTextColor(0,0,0);
$pdf->SetFont('Arial','',10);

$pdf->Cell(50,6,'Receipt ID:',0,0);
$pdf->Cell(60,6,$receiptId,0,0);
$pdf->Cell(30,6,'Reference:',0,0);
$pdf->Cell(0,6,$invoiceNo,0,1);

$pdf->Cell(50,6,'Sale Date:',0,0);
$pdf->Cell(60,6,$saleDate,0,0);
$pdf->Cell(30,6,'Payment Date:',0,0);
$pdf->Cell(0,6,$paymentDate,0,1);

$pdf->Cell(50,6,'Payment Time:',0,0);
$pdf->Cell(60,6,$paymentTime,0,0);
$pdf->Cell(30,6,'Method:',0,0);
$pdf->Cell(0,6,$paymentMethod,0,1);

$pdf->Ln(10);

// ===== TABLE HEADER =====
$pdf->SetFillColor($blue[0], $blue[1], $blue[2]);
$pdf->SetTextColor(255,255,255);
$pdf->SetFont('Arial','B',11);

$pdf->Cell(50,10,'Plan',1,0,'L',true);
$pdf->Cell(30,10,'Inst #',1,0,'C',true);
$pdf->Cell(40,10,'Amount',1,0,'R',true);
$pdf->Cell(40,10,'Remaining',1,0,'R',true);
$pdf->Cell(30,10,'Status',1,1,'C',true);

// ===== TABLE DATA =====
$pdf->SetFont('Arial','',11);
$pdf->SetTextColor(0,0,0);

$pdf->Cell(50,10,$planName,1);
$pdf->Cell(30,10,$installmentNo.'/'.$totalInst,1,0,'C');
$pdf->Cell(40,10,number_format((float)$installmentAmt,2),1,0,'R');
$pdf->Cell(40,10,number_format((float)$remaining,2),1,0,'R');
$pdf->Cell(30,10,$status,1,1,'C');

$pdf->Ln(10);

// ===== SUMMARY =====
$pdf->SetFont('Arial','B',11);
$pdf->Cell(0,7,'Payment Summary',0,1);

$pdf->SetFont('Arial','',11);

$pdf->Cell(120,8,'Installment Paid',1);
$pdf->Cell(0,8,number_format((float)$installmentAmt,2),1,1,'R');

$pdf->Cell(120,8,'Remaining Balance',1);
$pdf->Cell(0,8,number_format((float)$remaining,2),1,1,'R');

$pdf->Ln(12);

// ===== FOOTER =====
$pdf->SetTextColor(120,120,120);
$pdf->SetFont('Arial','',9);

$pdf->MultiCell(0,5,
"Splipay Payment Document

This receipt confirms that a payment has been successfully processed under the Buy Now Pay Later (BNPL) agreement.

All transactions are securely handled via ".$institution.". This document serves as an official confirmation of the installment payment made by the customer.

For any disputes, clarifications, or support requests, please contact our support team with your receipt reference number.

".$footer."
");


// ==========================
// SAVE FILE
// ==========================

if (!file_exists('invoices')) {
    mkdir('invoices', 0777, true);
}

$filename = "Receipt_" . ($invoiceNo ?: time()) . ".pdf";
$filePath = "invoices/" . $filename;

$pdf->Output('F', $filePath);

// ==========================
// RESPONSE (UNCHANGED)
// ========================== 

$baseUrl = "https://hexdive.com/pdf/";

$response = [
    "status" => "success",
    "invoice_no" => $invoiceNo,
    "file_path" => $filePath,
    "download_url" => $baseUrl . $filePath
];

header('Content-Type: application/json');
echo json_encode($response);

exit;