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

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';

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

$search = $_GET['q'] ?? '';
$date_from = $_GET['from'] ?? '';
$date_to = $_GET['to'] ?? '';

// بناء الاستعلام مع الفلترة
$sql = "SELECT p.*, s.name as supplier_name 
        FROM purchases p 
        LEFT JOIN suppliers s ON p.supplier_id = s.id 
        WHERE 1=1";

$params = [];
if ($search) {
    $sql .= " AND (s.name LIKE ? OR p.note LIKE ? OR p.id = ?)";
    $params[] = "%$search%";
    $params[] = "%$search%";
    $params[] = $search;
}
if ($date_from) {
    $sql .= " AND DATE(p.created_at) >= ?";
    $params[] = $date_from;
}
if ($date_to) {
    $sql .= " AND DATE(p.created_at) <= ?";
    $params[] = $date_to;
}

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

// حساب الإحصائيات للفواتير المعروضة
$stats = ['total' => 0, 'paid' => 0, 'count' => count($purchases)];
foreach ($purchases as $p) {
    $stats['total'] += $p['total'];
    $stats['paid'] += $p['paid'];
}
$stats['debt'] = $stats['total'] - $stats['paid'];
?>
<!doctype html>
<html lang="<?= $is_ar ? 'ar' : 'en' ?>" dir="<?= $is_ar ? 'rtl' : 'ltr' ?>">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <title><?= $is_ar ? 'سجل المشتريات | Top Accessories' : 'Purchase Log | Top Accessories' ?></title>
    
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link href="https://fonts.googleapis.com/css2?family=Cairo:wght@400;600;700&family=Plus+Jakarta+Sans:wght@400;600;700&display=swap" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    
    <style>
        :root {
            --primary: #2563eb;
            --bg: #f8fafc;
            --border: #e2e8f0;
            --card-shadow: 0 10px 40px -10px rgba(0, 0, 0, 0.05);
        }

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

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

        .container { max-width: 1200px; }

        /* Stats Section */
        .stat-card {
            background: white; border-radius: 20px; padding: 20px;
            border: 1px solid var(--border); box-shadow: var(--card-shadow);
            display: flex; align-items: center; gap: 15px;
        }
        .stat-icon {
            width: 48px; height: 48px; border-radius: 12px;
            display: flex; align-items: center; justify-content: center; font-size: 1.25rem;
        }

        /* Glass Card */
        .glass-card {
            background: white; border-radius: 24px; border: 1px solid var(--border);
            box-shadow: var(--card-shadow); overflow: hidden; margin-top: 30px;
        }

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

        .btn-view {
            background: var(--primary); color: white; border: none; border-radius: 10px;
            padding: 6px 16px; font-size: 0.85rem; font-weight: 600; text-decoration: none;
            transition: 0.2s;
        }
        .btn-view:hover { background: #1d4ed8; transform: translateY(-1px); color: white; }

        .status-badge {
            padding: 4px 12px; border-radius: 50px; font-size: 0.75rem; font-weight: 700;
        }
        .status-full { background: #f0fdf4; color: #166534; }
        .status-partial { background: #fffbeb; color: #92400e; }

        .form-pro { border-radius: 10px; border: 1px solid var(--border); padding: 8px 12px; font-size: 0.9rem; }
    </style>
</head>
<body>

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

    <div class="container">
        <!-- Header -->
        <div class="d-flex justify-content-between align-items-center mb-5">
            <div>
                <h1 class="fw-bold fs-3 m-0"><?= $is_ar ? 'سجل فواتير المشتريات' : 'Purchase Invoices Log' ?></h1>
                <p class="text-muted small m-0"><?= $is_ar ? 'استعراض وإدارة كافة عمليات الشراء السابقة' : 'Review and manage all previous purchase operations' ?></p>
            </div>
            <div class="d-flex gap-2">
                <a href="purchase_invoice.php" class="btn btn-primary rounded-pill px-4 fw-bold shadow-sm">+ <?= $is_ar ? 'فاتورة جديدة' : 'New Invoice' ?></a>
                <a href="index.php" class="btn btn-light rounded-pill px-4 fw-bold shadow-sm">🏠</a>
            </div>
        </div>

        <!-- Quick Stats -->
        <div class="row g-4">
            <div class="col-md-3">
                <div class="stat-card">
                    <div class="stat-icon" style="background: #eff6ff; color: #2563eb;">📑</div>
                    <div>
                        <div class="text-muted small"><?= $is_ar ? 'عدد الفواتير' : 'Total Invoices' ?></div>
                        <div class="fw-bold fs-5"><?= $stats['count'] ?></div>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="stat-card">
                    <div class="stat-icon" style="background: #f0fdf4; color: #10b981;">💰</div>
                    <div>
                        <div class="text-muted small"><?= $is_ar ? 'إجمالي المشتريات' : 'Total Purchases' ?></div>
                        <div class="fw-bold fs-5"><?= number_format($stats['total'], 2) ?></div>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="stat-card">
                    <div class="stat-icon" style="background: #fefce8; color: #ca8a04;">💳</div>
                    <div>
                        <div class="text-muted small"><?= $is_ar ? 'إجمالي المدفوع' : 'Total Paid' ?></div>
                        <div class="fw-bold fs-5"><?= number_format($stats['paid'], 2) ?></div>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="stat-card">
                    <div class="stat-icon" style="background: #fef2f2; color: #ef4444;">⚖️</div>
                    <div>
                        <div class="text-muted small"><?= $is_ar ? 'إجمالي الديون' : 'Total Remaining' ?></div>
                        <div class="fw-bold fs-5"><?= number_format($stats['debt'], 2) ?></div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Main Card -->
        <div class="glass-card">
            <!-- Filter Area -->
            <div class="filter-area">
                <form method="get" class="row g-3 align-items-end">
                    <div class="col-md-4">
                        <label class="small fw-bold mb-1"><?= $is_ar ? 'بحث (رقم الفاتورة، مورد، ملاحظة)' : 'Search (ID, Supplier, Note)' ?></label>
                        <input type="text" name="q" value="<?= esc($search) ?>" class="form-control form-pro" placeholder="...">
                    </div>
                    <div class="col-md-2">
                        <label class="small fw-bold mb-1"><?= $is_ar ? 'من تاريخ' : 'From Date' ?></label>
                        <input type="date" name="from" value="<?= esc($date_from) ?>" class="form-control form-pro">
                    </div>
                    <div class="col-md-2">
                        <label class="small fw-bold mb-1"><?= $is_ar ? 'إلى تاريخ' : 'To Date' ?></label>
                        <input type="date" name="to" value="<?= esc($date_to) ?>" class="form-control form-pro">
                    </div>
                    <div class="col-md-2">
                        <button type="submit" class="btn btn-dark w-100 rounded-pill fw-bold" style="padding: 9px;"><?= $is_ar ? 'تطبيق الفلتر' : 'Filter' ?></button>
                    </div>
                    <div class="col-md-2">
                        <a href="purchase_view.php" class="btn btn-outline-secondary w-100 rounded-pill fw-bold" style="padding: 9px;"><?= $is_ar ? 'إعادة تعيين' : 'Reset' ?></a>
                    </div>
                </form>
            </div>

            <!-- Table -->
            <div class="table-responsive">
                <table class="table">
                    <thead>
                        <tr>
                            <th># ID</th>
                            <th><?= $is_ar ? 'المورد' : 'Supplier' ?></th>
                            <th><?= $is_ar ? 'الإجمالي' : 'Total' ?></th>
                            <th><?= $is_ar ? 'المدفوع' : 'Paid' ?></th>
                            <th><?= $is_ar ? 'المتبقي' : 'Balance' ?></th>
                            <th><?= $is_ar ? 'الحالة' : 'Status' ?></th>
                            <th><?= $is_ar ? 'التاريخ' : 'Date' ?></th>
                            <th class="text-center"><?= $is_ar ? 'عرض' : 'View' ?></th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($purchases as $p): 
                            $remain = $p['total'] - $p['paid'];
                            $is_full = $remain <= 0;
                        ?>
                        <tr>
                            <td class="fw-bold text-primary">#<?= $p['id'] ?></td>
                            <td>
                                <div class="fw-600"><?= esc($p['supplier_name'] ?: ($is_ar ? 'نقدي' : 'Cash')) ?></div>
                                <div class="text-muted xsmall"><?= esc(substr($p['note'], 0, 30)) ?><?= strlen($p['note']) > 30 ? '...' : '' ?></div>
                            </td>
                            <td class="fw-bold"><?= number_format($p['total'], 2) ?></td>
                            <td class="text-success"><?= number_format($p['paid'], 2) ?></td>
                            <td class="<?= $remain > 0 ? 'text-danger fw-bold' : 'text-muted' ?>">
                                <?= number_format($remain, 2) ?>
                            </td>
                            <td>
                                <span class="status-badge <?= $is_full ? 'status-full' : 'status-partial' ?>">
                                    <?= $is_full ? ($is_ar ? 'مدفوع بالكامل' : 'Fully Paid') : ($is_ar ? 'متبقي مبالغ' : 'Partial') ?>
                                </span>
                            </td>
                            <td class="text-muted small">
                                <?= date('Y-m-d H:i', strtotime($p['created_at'])) ?>
                            </td>
                            <td class="text-center">
                                <a href="purchase_view_invoice.php?id=<?= $p['id'] ?>" class="btn-view" title="<?= $is_ar ? 'تفاصيل الفاتورة' : 'View Invoice' ?>">
                                    <?= $is_ar ? 'فتح' : 'Open' ?>
                                </a>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                        <?php if (empty($purchases)): ?>
                        <tr>
                            <td colspan="8" class="text-center py-5 text-muted">
                                <?= $is_ar ? 'لا توجد فواتير مطابقة للبحث.' : 'No invoices found matching your criteria.' ?>
                            </td>
                        </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>

        <div class="text-center mt-5 text-muted small">
            &copy; 2025 Top Accessories Tools &bull; Financial Records Management
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>