<?php
// --- PHP Error Tracking ---
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Include auth, DB, and Dompdf
include 'includes/auth.php';
include 'db.php';
require 'dompdf/vendor/autoload.php';
use Dompdf\Dompdf;

// Get customer ID from URL
$id = intval($_GET['id'] ?? 0);
if (!$id) {
    die("Invalid customer ID.");
}

// Fetch customer details
$customer_result = $conn->query("SELECT * FROM customers WHERE id = $id");
if(!$customer_result){
    die("Error fetching customer: " . $conn->error);
}
$customer = $customer_result->fetch_assoc();
if (!$customer) {
    die("Customer not found.");
}

// Fetch purchases
$purchases = $conn->query("
    SELECT s.id, s.sale_date, s.total AS total_amount, s.payment_method, s.loyalty_points
    FROM sales s
    WHERE s.customer_id = $id
    ORDER BY s.sale_date DESC
");
if(!$purchases){
    die("Error fetching purchases: " . $conn->error);
}

// Build HTML for statement
$html = '<h2 style="text-align:center;">Customer Statement</h2>';
$html .= '<h3>Customer: ' . htmlspecialchars($customer['name']) . '</h3>';
$html .= '<p><strong>Phone:</strong> ' . htmlspecialchars($customer['phone']) . ' &nbsp; <strong>Email:</strong> ' . htmlspecialchars($customer['email']) . '</p>';
$html .= '<hr>';

$html .= '<h4>Purchases</h4>';

$total_purchases = 0;
$total_loyalty = 0;

while ($sale = $purchases->fetch_assoc()) {
    $html .= "<h5>Sale ID: {$sale['id']} | Date: {$sale['sale_date']} | Payment Method: {$sale['payment_method']} | Loyalty Points: {$sale['loyalty_points']}</h5>";
    $total_loyalty += $sale['loyalty_points'];

    // Fetch sale items
    $items = $conn->query("
        SELECT si.*, p.name AS name, p.sku 
        FROM sale_items si
        LEFT JOIN products p ON si.product_id = p.id
        WHERE si.sale_id = {$sale['id']}
    ");
    if(!$items){
        die("Error fetching sale items for sale ID {$sale['id']}: " . $conn->error);
    }

    $html .= '<table width="100%" border="1" cellpadding="6" cellspacing="0" style="margin-bottom:15px;">
                <tr style="background:#000;color:#fff;text-align:center;">
                    <th>#</th>
                    <th>SKU</th>
                    <th>Product</th>
                    <th>Price (MK)</th>
                    <th>Qty</th>
                    <th>VAT (MK)</th>
                    <th>Total (MK)</th>
                </tr>';

    $item_idx = 1;
    $sale_total = 0;

    while ($item = $items->fetch_assoc()) {
        $line_total = $item['price'] * $item['qty'];
        $vat = $line_total * ($item['vat'] / 100);
        $total_line = $line_total + $vat;
        $sale_total += $total_line;

        $html .= "<tr>
                    <td>{$item_idx}</td>
                    <td>{$item['sku']}</td>
                    <td>{$item['name']}</td>
                    <td style='text-align:right;'>" . number_format($item['price'],2) . "</td>
                    <td style='text-align:center;'>{$item['qty']}</td>
                    <td style='text-align:right;'>" . number_format($vat,2) . "</td>
                    <td style='text-align:right;'>" . number_format($total_line,2) . "</td>
                  </tr>";
        $item_idx++;
    }

    $html .= '</table>';
    $html .= "<p style='text-align:right;font-weight:bold;'>Sale Total: MK " . number_format($sale_total,2) . "</p>";
    $total_purchases += $sale_total;
}

// Grand Totals
$html .= "<h3 style='text-align:right;'>Total Purchases: MK " . number_format($total_purchases,2) . "</h3>";
$html .= "<h3 style='text-align:right;'>Total Loyalty Points Earned: " . number_format($total_loyalty,2) . "</h3>";

// Render PDF
try {
    $dompdf = new Dompdf();
    $dompdf->loadHtml($html);
    $dompdf->setPaper('A4','portrait');
    $dompdf->render();
    $dompdf->stream("customer_statement_{$customer['id']}.pdf", ["Attachment" => true]);
} catch (Exception $e) {
    echo "Error generating PDF: " . $e->getMessage();
}

exit;
?>
