<?php   
include '../includes/config.php';
error_reporting(E_ALL);
ini_set('display_errors', 1);

$invoice = $_GET['invoice'] ?? '';
$customer_id = $_GET['customer_id'] ?? '';
$id = $_GET['id'] ?? '';

if (empty($invoice) && empty($customer_id) && empty($id)) {
    die("Invalid Request");
}

// Agar sirf ID diya gaya ho to uska invoice nikaal lo
if (!empty($id)) {
    $stmt2 = $conn->prepare("SELECT invoice FROM customer_installments WHERE id = :id LIMIT 1");
    $stmt2->execute([':id' => $id]);
    $row = $stmt2->fetch(PDO::FETCH_ASSOC);
    if ($row) {
        $invoice = $row['invoice'];
    } else {
        die("Invalid Installment ID");
    }
}

// Ab poore invoice ke installments fetch karo
$sql = "
    SELECT 
        ci.id,
        ci.invoice,
        ci.customer_id,
        c.name AS customer_name,
        ci.installment_no,
        ci.amount,
        ci.due_date,
        ci.status,
        ci.paid_date
    FROM customer_installments ci
    INNER JOIN contacts c ON ci.customer_id = c.id
    WHERE ci.invoice = :invoice
    ORDER BY ci.installment_no ASC
";

$stmt = $conn->prepare($sql);
$stmt->execute([':invoice' => $invoice]);
$installments = $stmt->fetchAll(PDO::FETCH_ASSOC);

if (!$installments) {
    die("No Installments Found");
}

// Totals
$total_amount = array_sum(array_column($installments, 'amount'));
$total_paid   = 0;
$total_remain = 0;
foreach ($installments as $inst) {
    if ($inst['status'] === 'paid') {
        $total_paid += $inst['amount'];
    } else {
        $total_remain += $inst['amount'];
    }
}

$customer_name = $installments[0]['customer_name'];
$invoice_no    = $installments[0]['invoice'];
$date_now      = date("d-m-Y H:i");

// --- Company Details (You can make this dynamic from DB/settings)
$company_name  = "ABC Traders Pvt Ltd";
$company_addr  = "Main Bazar, Lahore, Pakistan";
$company_phone = "+92 300 1234567";
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Receipt</title>
<style>
    body {
        width: 80mm;
        font-family: 'Courier New', monospace;
        font-size: 12px;
        margin: 0 auto;
    }
    .center { text-align: center; }
    .bold { font-weight: bold; }
    .line { border-top: 1px dashed #000; margin: 5px 0; }
    table { width: 100%; border-collapse: collapse; font-size: 12px; }
    td, th { padding: 2px 0; }
    .right { text-align: right; }
    .left { text-align: left; }
    @media print {
        body { margin: 0; }
        .no-print { display: none; }
    }
</style>
</head>
<body>

<div class="center bold"><?= strtoupper($company_name) ?></div>
<div class="center"><?= $company_addr ?></div>
<div class="center"> <?= $company_phone ?></div>
<div class="line"></div>

<div class="center bold"> Customer Receipt </div>
<div class="line"></div>

<table>
    <tr><td class="left">Invoice:</td><td class="right"><?= $invoice_no ?></td></tr>
    <tr><td class="left">Customer:</td><td class="right"><?= htmlspecialchars($customer_name) ?></td></tr>
    <tr><td class="left">Date:</td><td class="right"><?= $date_now ?></td></tr>
</table>

<div class="line"></div>
<div class="bold">Installments Summary</div>
<table>
    <thead>
        <tr>
            <th class="left">#</th>
            <th class="left">Due</th>
            <th class="right">Amt</th>
            <th class="right">Status</th>
        </tr>
    </thead>
    <tbody>
        <?php foreach ($installments as $inst): ?>
        <tr>
            <td><?= $inst['installment_no'] ?></td>
            <td><?= date("d-m-Y", strtotime($inst['due_date'])) ?></td>
            <td class="right"><?= number_format($inst['amount'], 2) ?></td>
            <td class="right"><?= ucfirst($inst['status']) ?></td>
        </tr>
        <?php endforeach; ?>
    </tbody>
</table>

<div class="line"></div>
<table>
    <tr><td class="left">Total:</td><td class="right"><?= number_format($total_amount, 2) ?></td></tr>
    <tr><td class="left">Paid:</td><td class="right"><?= number_format($total_paid, 2) ?></td></tr>
    <tr><td class="left">Remaining:</td><td class="right"><?= number_format($total_remain, 2) ?></td></tr>
</table>

<?php if ($total_remain > 0): ?>
<div class="line"></div>
<div class="bold"> Remaining Installments</div>
<table>
    <thead>
        <tr>
            <th class="left">#</th>
            <th class="left">Due Date</th>
            <th class="right">Amt</th>
        </tr>
    </thead>
    <tbody>
        <?php foreach ($installments as $inst): ?>
            <?php if ($inst['status'] !== 'paid'): ?>
                <tr>
                    <td><?= $inst['installment_no'] ?></td>
                    <td><?= date("d-m-Y", strtotime($inst['due_date'])) ?></td>
                    <td class="right"><?= number_format($inst['amount'], 2) ?></td>
                </tr>
            <?php endif; ?>
        <?php endforeach; ?>
    </tbody>
</table>
<?php endif; ?>

<div class="line"></div>
<div class="center">Thank you for your payment</div>
<div class="center no-print">
    <button onclick="window.print()">🖨 Print</button>
</div>

</body>
</html>
