<?php
/**
 * customer_statement.php
 * Premium Customer Statement with Linked Products & PDF Export
 */

require_once __DIR__ . '/config/db.php';
require_once __DIR__ . '/src/auth.php';
require_login();

date_default_timezone_set('Asia/Beirut');

// --- إعدادات اللغة ---
if (session_status() === PHP_SESSION_NONE) session_start();
$lang = $_GET['lang'] ?? ($_SESSION['lang'] ?? 'ar');
if (isset($_GET['lang'])) { $_SESSION['lang'] = $_GET['lang'] === 'ar' ? 'ar' : 'en'; $lang = $_SESSION['lang']; }
$is_ar = $lang === 'ar';
$dir = $is_ar ? 'rtl' : 'ltr';

function esc($v){ return htmlspecialchars($v ?? '', ENT_QUOTES, 'UTF-8'); }

// --- الترجمة ---
$T = [
    'en' => [
        'title' => 'Account Statement',
        'customer' => 'Customer',
        'phone' => 'Phone',
        'balance' => 'Outstanding Balance',
        'from' => 'From',
        'to' => 'To',
        'filter' => 'Apply Filter',
        'all' => 'All Records',
        'last7' => 'Last 7 Days',
        'last30' => 'Last 30 Days',
        'month' => 'This Month',
        'amount' => 'Amount',
        'type' => 'Type',
        'desc' => 'Transaction Details',
        'products' => 'Items Breakdown',
        'date' => 'Date/Time',
        'actions' => 'Invoice',
        'export' => 'Export PDF',
        'print' => 'Print',
        'back' => 'Back to Debts',
        'debt' => 'Debt',
        'payment' => 'Payment'
    ],
    'ar' => [
        'title' => 'كشف حساب عميل',
        'customer' => 'العميل',
        'phone' => 'الهاتف',
        'balance' => 'الرصيد المستحق',
        'from' => 'من تاريخ',
        'to' => 'إلى تاريخ',
        'filter' => 'تصفية النتائج',
        'all' => 'كل الفترات',
        'last7' => 'آخر 7 أيام',
        'last30' => 'آخر 30 يوم',
        'month' => 'هذا الشهر',
        'amount' => 'المبلغ',
        'type' => 'النوع',
        'desc' => 'تفاصيل العملية',
        'products' => 'الأصناف المرتبطة',
        'date' => 'التاريخ والوقت',
        'actions' => 'الفاتورة',
        'export' => 'تصدير PDF',
        'print' => 'طباعة',
        'back' => 'العودة للديون',
        'debt' => 'دين',
        'payment' => 'سداد'
    ]
];
$t = $T[$lang];

// --- جلب البيانات الأساسية ---
$id = intval($_GET['id'] ?? 0);
$stmt = $pdo->prepare("SELECT * FROM customers WHERE id = ? LIMIT 1");
$stmt->execute([$id]);
$cust = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$cust) {
    die($is_ar ? 'العميل غير موجود' : 'Customer not found');
}

// --- معالجة الفلاتر ---
$from = $_GET['from'] ?? '';
$to = $_GET['to'] ?? '';
$range = $_GET['range'] ?? 'all';

if ($range === 'last7') { $from = date('Y-m-d', strtotime('-7 days')); $to = date('Y-m-d'); }
elseif ($range === 'last30') { $from = date('Y-m-d', strtotime('-30 days')); $to = date('Y-m-d'); }
elseif ($range === 'month') { $from = date('Y-m-01'); $to = date('Y-m-d'); }

// --- الاستعلام عن الحركات ---
$sql = "SELECT * FROM customer_transactions WHERE customer_id = ?";
$params = [$id];

if ($from && $to) {
    $sql .= " AND date BETWEEN ? AND ?";
    $params[] = "$from 00:00:00";
    $params[] = "$to 23:59:59";
}

$sql .= " ORDER BY date DESC";
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

// حساب الملخصات
$total_debit = 0; $total_payment = 0;
foreach($rows as $r) { if($r['type']=='debt') $total_debit += $r['amount']; else $total_payment += $r['amount']; }

// تحديد حقل اسم المنتج (دعم اللغتين)
$cols = $pdo->query("SHOW COLUMNS FROM products")->fetchAll(PDO::FETCH_COLUMN);
$nameField = in_array('name_en', $cols) ? 'name_en' : (in_array('name_ar', $cols) ? 'name_ar' : 'name');
?>
<!doctype html>
<html lang="<?= $lang ?>" dir="<?= $dir ?>">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <title><?= esc($t['title']) ?> | <?= esc($cust['name']) ?></title>
    
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link href="https://fonts.googleapis.com/css2?family=Cairo:wght@400;600;700;800&family=Plus+Jakarta+Sans:wght@400;500;600;700;800&display=swap" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
    
    <style>
        :root {
            --primary: #2563eb;
            --success: #10b981;
            --danger: #f43f5e;
            --bg: #f8fafc;
            --surface: #ffffff;
            --border: #e2e8f0;
        }

        body {
            font-family: <?= $is_ar ? "'Cairo', sans-serif" : "'Plus Jakarta Sans', sans-serif" ?>;
            background-color: var(--bg);
            color: #1e293b;
            padding: 30px 0;
        }

        .bg-pattern {
            position: fixed; top: 0; left: 0; width: 100%; height: 100%; z-index: -1;
            background-image: radial-gradient(#cbd5e1 0.8px, transparent 0.8px);
            background-size: 24px 24px; opacity: 0.3;
        }

        .container { max-width: 1200px; }

        /* Document Styling */
        .statement-paper {
            background: white; border-radius: 32px; padding: 50px;
            border: 1px solid var(--border); box-shadow: 0 20px 50px -12px rgba(0, 0, 0, 0.05);
            position: relative; overflow: hidden;
        }

        .statement-paper::before {
            content: ""; position: absolute; top: 0; left: 0; right: 0; height: 8px;
            background: linear-gradient(90deg, var(--primary), var(--success));
        }

        /* Profile Header */
        .profile-section {
            background: #f8fafc; border-radius: 24px; padding: 30px;
            margin-bottom: 35px; border: 1px solid var(--border);
            display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 20px;
        }

        .balance-badge {
            background: white; border-radius: 18px; padding: 15px 25px;
            border: 1px solid var(--border); text-align: center;
        }
        .balance-val { font-size: 1.8rem; font-weight: 800; display: block; }
        .balance-label { font-size: 0.75rem; text-transform: uppercase; font-weight: 800; color: #64748b; letter-spacing: 0.05em; }

        /* Stats Row */
        .stats-row { display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 15px; margin-bottom: 30px; }
        .stat-box { background: white; border: 1px solid var(--border); border-radius: 16px; padding: 15px; text-align: center; }
        .stat-box small { display: block; color: #64748b; font-weight: 700; font-size: 0.7rem; text-transform: uppercase; margin-bottom: 5px; }
        .stat-box span { font-weight: 800; font-size: 1.2rem; }

        /* Table */
        .table thead th {
            background: #f8fafc; color: #64748b; font-size: 0.75rem;
            text-transform: uppercase; padding: 18px 20px; font-weight: 800; border: 0;
        }
        .table tbody td { padding: 18px 20px; vertical-align: middle; border-bottom: 1px solid #f1f5f9; }

        .item-row { font-size: 0.85rem; color: #64748b; padding: 2px 0; display: block; }
        .item-sku { font-family: monospace; font-weight: 700; color: var(--primary); background: #eff6ff; padding: 1px 4px; border-radius: 4px; }

        /* Buttons */
        .btn-lux { border-radius: 14px; padding: 10px 22px; font-weight: 700; transition: 0.3s; display: inline-flex; align-items: center; gap: 8px; border: 1.5px solid var(--border); background: #fff; color: #64748b; text-decoration: none; }
        .btn-lux:hover { border-color: var(--primary); color: var(--primary); transform: translateY(-2px); }
        .btn-primary-lux { background: var(--primary); color: white; border: none; }
        .btn-primary-lux:hover { background: #1d4ed8; color: white; box-shadow: 0 10px 15px -3px rgba(37, 99, 235, 0.2); }

        .type-pill { padding: 4px 12px; border-radius: 50px; font-size: 0.75rem; font-weight: 800; }
        .type-debt { background: #fef2f2; color: #dc2626; }
        .type-payment { background: #f0fdf4; color: #16a34a; }

        @media print {
            body { background: white; padding: 0; }
            .bg-pattern, .no-print, .filter-form { display: none !important; }
            .statement-paper { box-shadow: none; border: none; padding: 0; }
            .statement-paper::before { display: none; }
        }
    </style>
</head>
<body>

<div class="bg-pattern"></div>

<div class="container">
    
    <!-- Top Actions -->
    <div class="d-flex justify-content-between align-items-center mb-4 no-print">
        <a href="debts.php" class="btn-lux"><i class="fa fa-arrow-<?= $is_ar?'right':'left' ?>"></i> <?= esc($t['back']) ?></a>
        <div class="d-flex gap-2">
            <button onclick="exportPDF()" class="btn-lux text-danger border-danger border-opacity-25"><i class="fa fa-file-pdf"></i> <?= esc($t['export']) ?></button>
            <button onclick="window.print()" class="btn-lux"><i class="fa fa-print"></i> <?= esc($t['print']) ?></button>
            <a href="?lang=<?= $is_ar?'en':'ar' ?>&id=<?= $id ?>" class="btn-lux">🌐 <?= $is_ar?'English':'العربية' ?></a>
        </div>
    </div>

    <!-- Filter Form -->
    <div class="glass-card mb-4 no-print" style="background:white; border-radius: 24px; padding: 25px; border: 1px solid var(--border);">
        <form method="get" class="row g-3 align-items-end">
            <input type="hidden" name="id" value="<?= $id ?>">
            <input type="hidden" name="lang" value="<?= $lang ?>">
            <div class="col-md-2">
                <label class="small fw-bold text-muted mb-1"><?= esc($t['from']) ?></label>
                <input type="date" name="from" value="<?= esc($from) ?>" class="form-control rounded-3">
            </div>
            <div class="col-md-2">
                <label class="small fw-bold text-muted mb-1"><?= esc($t['to']) ?></label>
                <input type="date" name="to" value="<?= esc($to) ?>" class="form-control rounded-3">
            </div>
            <div class="col-md-4">
                <label class="small fw-bold text-muted mb-1"><?= esc($t['filter']) ?></label>
                <select name="range" class="form-select rounded-3" onchange="this.form.submit()">
                    <option value="all" <?= $range=='all'?'selected':'' ?>><?= esc($t['all']) ?></option>
                    <option value="last7" <?= $range=='last7'?'selected':'' ?>><?= esc($t['last7']) ?></option>
                    <option value="last30" <?= $range=='last30'?'selected':'' ?>><?= esc($t['last30']) ?></option>
                    <option value="month" <?= $range=='month'?'selected':'' ?>><?= esc($t['month']) ?></option>
                </select>
            </div>
            <div class="col-md-4">
                <button type="submit" class="btn btn-primary-lux rounded-pill w-100 py-2 fw-bold"><?= esc($t['filter']) ?></button>
            </div>
        </form>
    </div>

    <!-- Statement Paper -->
    <div class="statement-paper" id="captureArea">
        
        <!-- Document Header -->
        <div class="d-flex justify-content-between align-items-start mb-5 border-bottom pb-4">
            <div>
                <h2 class="fw-800 text-primary m-0">TOP ACCESSORIES</h2>
                <p class="text-muted small m-0"><?= $is_ar ? 'سجل المعاملات المالية المعتمد' : 'Certified Financial Transaction Ledger' ?></p>
            </div>
            <div class="text-<?= $is_ar?'start':'end' ?>">
                <div class="fw-800"><?= esc($t['title']) ?></div>
                <div class="text-muted small"><?= date('M d, Y') ?></div>
            </div>
        </div>

        <!-- Customer Profile -->
        <div class="profile-section">
            <div>
                <h4 class="fw-800 m-0"><?= esc($cust['name']) ?></h4>
                <div class="text-muted fw-600 mt-1"><i class="fa fa-phone me-1"></i> <?= esc($cust['phone']) ?></div>
            </div>
            <div class="balance-badge shadow-sm">
                <span class="balance-label"><?= esc($t['balance']) ?></span>
                <span class="balance-val <?= $cust['balance'] > 0 ? 'text-danger' : 'text-success' ?>">
                    $<?= number_format($cust['balance'], 2) ?>
                </span>
            </div>
        </div>

        <!-- Quick Summary Stats -->
        <div class="stats-row">
            <div class="stat-box">
                <small><?= $is_ar?'إجمالي الديون':'Total Debits' ?></small>
                <span class="text-danger">$<?= number_format($total_debit, 2) ?></span>
            </div>
            <div class="stat-box">
                <small><?= $is_ar?'إجمالي المدفوع':'Total Payments' ?></small>
                <span class="text-success">$<?= number_format($total_payment, 2) ?></span>
            </div>
            <div class="stat-box">
                <small><?= $is_ar?'عدد العمليات':'Entries' ?></small>
                <span><?= count($rows) ?></span>
            </div>
            <div class="stat-box">
                <small><?= $is_ar?'فترة الكشف':'Period' ?></small>
                <span class="small" style="font-size: 0.8rem;"><?= $from ?: 'START' ?> ➔ <?= $to ?: 'NOW' ?></span>
            </div>
        </div>

        <!-- Transactions Table -->
        <div class="table-responsive">
            <table class="table align-middle">
                <thead>
                    <tr>
                        <th style="width: 15%;"><?= esc($t['date']) ?></th>
                        <th style="width: 10%;" class="text-center"><?= esc($t['type']) ?></th>
                        <th style="width: 20%;"><?= esc($t['desc']) ?></th>
                        <th style="width: 35%;"><?= esc($t['products']) ?></th>
                        <th style="width: 12%;" class="text-center"><?= esc($t['amount']) ?></th>
                        <th style="width: 8%;" class="text-center"><?= esc($t['actions']) ?></th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (!$rows): ?>
                        <tr><td colspan="6" class="text-center py-5 text-muted fw-bold"><?= esc($t['no_results']) ?></td></tr>
                    <?php else: foreach($rows as $r): ?>
                        <?php
                        $invoice_id = null;
                        if (!empty($r['sale_id'])) {
                            $invoice_id = intval($r['sale_id']);
                        } elseif (preg_match('/INV-[A-Za-z0-9\-]+/', $r['note'], $m)) {
                            $invoice_no = $m[0];
                            $find = $pdo->prepare("SELECT id FROM sales WHERE invoice_no = ? LIMIT 1");
                            $find->execute([$invoice_no]);
                            $invoice_id = $find->fetchColumn();
                        }

                        // جلب المنتجات المرتبطة
                        $product_html = '';
                        if ($invoice_id) {
                            $ps = $pdo->prepare("SELECT si.qty, p.$nameField as pname, p.sku FROM sale_items si LEFT JOIN products p ON p.id = si.product_id WHERE si.sale_id = ?");
                            $ps->execute([$invoice_id]);
                            $plist = $ps->fetchAll(PDO::FETCH_ASSOC);
                            foreach ($plist as $p) {
                                $product_html .= "<span class='item-row'><span class='item-sku'>".esc($p['sku'])."</span> ".esc($p['pname'])." <b class='text-dark'>×".$p['qty']."</b></span>";
                            }
                        }
                        ?>
                        <tr>
                            <td class="small fw-bold text-muted"><?= date('d M, H:i', strtotime($r['date'])) ?></td>
                            <td class="text-center">
                                <span class="type-pill <?= $r['type']=='debt' ? 'type-debt' : 'type-payment' ?>">
                                    <?= $r['type']=='debt' ? esc($t['debt']) : esc($t['payment']) ?>
                                </span>
                            </td>
                            <td class="fw-600 small"><?= esc($r['note']) ?></td>
                            <td class="small"><?= $product_html ?: '<span class="text-muted">—</span>' ?></td>
                            <td class="text-center fw-800 fs-6 <?= $r['type']=='debt' ? 'text-danger' : 'text-success' ?>">
                                $<?= number_format($r['amount'], 2) ?>
                            </td>
                            <td class="text-center">
                                <?php if ($invoice_id): ?>
                                    <a href="sale_view.php?id=<?= $invoice_id ?>&lang=<?= $lang ?>" target="_blank" class="text-primary" title="View Invoice">
                                        <i class="fa fa-receipt fa-lg"></i>
                                    </a>
                                <?php else: ?>
                                    <span class="text-muted small">—</span>
                                <?php endif; ?>
                            </td>
                        </tr>
                    <?php endforeach; endif; ?>
                </tbody>
            </table>
        </div>

        <!-- Footer -->
        <div class="mt-5 pt-4 border-top text-center">
            <p class="text-muted small"><?= $is_ar ? 'شكراً لثقتكم بنا. هذا الكشف صادر آلياً ولا يحتاج لختم.' : 'Thank you for your business. This is an electronically generated statement.' ?></p>
            <div class="fw-bold text-primary">Top Accessories &bull; 2025</div>
        </div>
    </div>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>

<script>
async function exportPDF(){
    const { jsPDF } = window.jspdf;
    const element = document.querySelector('#captureArea');
    
    // إشعار تحميل بسيط
    const btn = document.querySelector('.btn-lux.text-danger');
    const oldHtml = btn.innerHTML;
    btn.innerHTML = '<i class="fa fa-spinner fa-spin"></i> Generating...';

    try {
        const canvas = await html2canvas(element, { 
            scale: 2,
            useCORS: true,
            logging: false,
            backgroundColor: "#ffffff"
        });
        const imgData = canvas.toDataURL('image/png');
        const pdf = new jsPDF('p', 'mm', 'a4');
        const pdfWidth = pdf.internal.pageSize.getWidth();
        const pdfHeight = (canvas.height * pdfWidth) / canvas.width;
        
        pdf.addImage(imgData, 'PNG', 0, 0, pdfWidth, pdfHeight);
        pdf.save('Statement_<?= str_replace(" ", "_", $cust['name']) ?>.pdf');
    } catch (e) {
        console.error(e);
        alert('Failed to generate PDF');
    } finally {
        btn.innerHTML = oldHtml;
    }
}
</script>

</body>
</html>