<?php
require_once "../config/db.php";
require_once "../config/app.php";
require_once "../vendor/fpdf/fpdf.php";

$id = (int) ($_GET['id'] ?? 0);

if(!$id){
    die("Invalid Invoice");
}

// ================= DATA =================
$invoice = $conn->query("
SELECT i.*, c.name, c.phone, c.email
FROM invoices i
JOIN customers c ON i.customer_id = c.id
WHERE i.id = $id
")->fetch_assoc();

if(!$invoice){
    die("Invoice not found");
}

$items = $conn->query("
SELECT ii.*, s.service_name 
FROM invoice_items ii
LEFT JOIN services s ON ii.service_id = s.id
WHERE ii.invoice_id = $id
");

$paid = $conn->query("
SELECT IFNULL(SUM(amount),0) as total 
FROM payments WHERE invoice_id=$id
")->fetch_assoc()['total'];

$pending = $invoice['total'] - $paid;

// ================= PAYMENTS =================
$payments = $conn->query("
SELECT amount, payment_date, method 
FROM payments 
WHERE invoice_id=$id
ORDER BY payment_date ASC
");

// ================= STATUS =================
if($pending <= 0){
    $status = "PAID";
    $statusColor = [40,167,69];
}elseif($paid > 0){
    $status = "PARTIAL";
    $statusColor = [255,193,7];
}else{
    $status = "PENDING";
    $statusColor = [220,53,69];
}

// ================= INVOICE NUMBER =================
$invoice_no = "DV-INV-" . date('Y') . "-" . str_pad($id, 5, '0', STR_PAD_LEFT);

// ================= PDF =================
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetMargins(10,10,10);

// ================= HEADER (LIGHT GREY) =================
$pdf->SetFillColor(245,247,250);
$pdf->Rect(0,0,210,28,'F');

// LOGO
$logo = $_SERVER['DOCUMENT_ROOT'].'/assets/images/logo.png';
if(file_exists($logo)){
    $pdf->Image($logo, 10, 6, 20);
}

// COMPANY NAME
$pdf->SetXY(35,8);
$pdf->SetFont('Arial','B',14);
//$pdf->Cell(80,6, APP_NAME,0,0,'L');

// RIGHT INFO
$pdf->SetXY(120,8);
$pdf->SetFont('Arial','',10);
$pdf->Cell(80,5, COMPANY_PHONE,0,2,'R');
$pdf->Cell(80,5, COMPANY_EMAIL,0,2,'R');

$pdf->Ln(18);

// ================= STATUS =================
$pdf->SetFillColor($statusColor[0], $statusColor[1], $statusColor[2]);
$pdf->SetTextColor(255,255,255);
$pdf->SetXY(150,30);
$pdf->SetFont('Arial','B',10);
$pdf->Cell(40,8,$status,0,0,'C',true);

$pdf->SetTextColor(0,0,0);

// ================= TITLE =================
$pdf->Ln(8);
$pdf->SetFont('Arial','B',18);
$pdf->Cell(0,10,'INVOICE',0,1,'C');

$pdf->Ln(8);

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

$pdf->Cell(100,6,'Bill To:',0,0);
$pdf->Cell(0,6,$invoice_no,0,1,'R');

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

$pdf->Cell(100,6,$invoice['name'],0,0);
$pdf->Cell(0,6,'Date: '.$invoice['invoice_date'],0,1,'R');

$pdf->Cell(100,6,$invoice['email'],0,0);
$pdf->Cell(0,6,'Due: '.$invoice['due_date'],0,1,'R');

$pdf->Cell(100,6,$invoice['phone'],0,1);

$pdf->Ln(12);

// ================= TABLE =================
$pdf->SetFillColor(230,230,230);
$pdf->SetFont('Arial','B',11);

$pdf->Cell(130,12,'Service',1,0,'L',true);
$pdf->Cell(60,12,'Amount',1,1,'R',true);

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

$total = 0;

while($row = $items->fetch_assoc()){
    $desc = trim($row['description']);
    if(empty($desc)){
        $desc = $row['service_name'] ?: 'Service';
    }

    $amount = (float)$row['amount'];
    $total += $amount;

    $pdf->Cell(130,12,$desc,1);
    $pdf->Cell(60,12,'Rs. '.number_format($amount,2),1,1,'R');
}

// ================= TOTAL =================
$pdf->Ln(8);
$pdf->SetFont('Arial','B',11);

$pdf->Cell(130,10,'Total',1);
$pdf->Cell(60,10,'Rs. '.number_format($total,2),1,1,'R');

$pdf->Cell(130,10,'Paid',1);
$pdf->Cell(60,10,'Rs. '.number_format($paid,2),1,1,'R');

$pdf->Cell(130,10,'Pending',1);
$pdf->Cell(60,10,'Rs. '.number_format($pending,2),1,1,'R');

// ================= PAYMENT HISTORY =================
$pdf->Ln(12);

$pdf->SetFont('Arial','B',12);
$pdf->Cell(0,8,'Payment History',0,1);

$pdf->SetFillColor(230,230,230);
$pdf->SetFont('Arial','B',10);

$pdf->Cell(60,10,'Date',1);
$pdf->Cell(60,10,'Method',1);
$pdf->Cell(70,10,'Amount',1,1,'R');

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

if($payments->num_rows > 0){
    while($p = $payments->fetch_assoc()){
        $pdf->Cell(60,10,$p['payment_date'],1);
        $pdf->Cell(60,10,$p['method'],1);
        $pdf->Cell(70,10,'Rs. '.number_format($p['amount'],2),1,1,'R');
    }
}else{
    $pdf->Cell(190,10,'No payments yet',1,1,'C');
}

// ================= NOTES =================
$pdf->Ln(12);

$pdf->SetFont('Arial','B',11);
$pdf->Cell(0,6,'Notes:',0,1);

$pdf->SetFont('Arial','',10);
$pdf->MultiCell(0,6,
"Payment due within 7 days.\n".
"For support contact us anytime."
);

// ================= SIGNATURE =================
$pdf->Ln(15);

$stamp = $_SERVER['DOCUMENT_ROOT'].'/assets/images/stamp.png';
if(file_exists($stamp)){
    $pdf->Image($stamp, 70, $pdf->GetY()-10, 40, 40);
}

$sign = $_SERVER['DOCUMENT_ROOT'].'/assets/images/signature.png';
if(file_exists($sign)){
    $pdf->Image($sign, 140, $pdf->GetY(), 35);
}

$pdf->Ln(25);

$pdf->SetFont('Arial','B',10);
$pdf->Cell(0,6,'Authorized Signature',0,1,'R');

// ================= FOOTER =================
$pdf->Ln(5);

$pdf->SetFont('Arial','I',10);
$pdf->Cell(0,8,'Thank you for your business!',0,1,'C');

$pdf->Output();
exit;