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

// -- إدارة اللغة --
$allowed_langs = ['en','ar'];
if (isset($_GET['lang']) && in_array($_GET['lang'], $allowed_langs)) {
    $_SESSION['lang'] = $_GET['lang'];
}
$lang = $_SESSION['lang'] ?? 'en';
$is_ar = $lang === 'ar';

$L = [
    'en' => [
        'title' => 'Sales Management',
        'new_sale' => 'New Invoice',
        'home' => 'Dashboard',
        'search' => 'Search invoices...',
        'from' => 'Start Date',
        'to' => 'End Date',
        'invoice' => 'Invoice #',
        'customer' => 'Customer',
        'total' => 'Total',
        'paid' => 'Paid',
        'due' => 'Remaining',
        'profit' => 'Profit',
        'payment' => 'Method',
        'date' => 'Date',
        'actions' => 'Control',
        'no_sales' => 'No invoices found for this period',
        'total_sales' => 'Period Sales',
        'total_paid' => 'Collected',
        'total_due' => 'Pending Debt',
        'view' => 'View',
        'edit' => 'Edit',
        'print' => 'Print',
        'delete' => 'Delete',
        'confirm_delete' => 'Delete this invoice permanently? This will restore stock, adjust customer balance, and clean ledger/cash logs.',
        'lang_switch' => 'العربية',
        'filter' => 'Filter Results',
        'status' => 'Status',
        'all' => 'All Status',
        'paid_status' => 'Fully Paid',
        'partial_status' => 'Partial',
        'unpaid_status' => 'Unpaid',
        'period_profit' => "Period Profit",
        'period_cash' => "Cash Received",
    ],
    'ar' => [
        'title' => 'إدارة المبيعات',
        'new_sale' => 'فاتورة جديدة',
        'home' => 'الرئيسية',
        'search' => 'بحث عن فاتورة...',
        'from' => 'من تاريخ',
        'to' => 'إلى تاريخ',
        'invoice' => 'رقم الفاتورة',
        'customer' => 'العميل',
        'total' => 'الإجمالي',
        'paid' => 'المدفوع',
        'due' => 'المتبقي',
        'profit' => 'الربح',
        'payment' => 'الدفع',
        'date' => 'التاريخ',
        'actions' => 'العمليات',
        'no_sales' => 'لا توجد فواتير لهذه الفترة',
        'total_sales' => 'مبيعات الفترة',
        'total_paid' => 'المبالغ المحصلة',
        'total_due' => 'الديون المتبقية',
        'view' => 'عرض',
        'edit' => 'تعديل',
        'print' => 'طباعة',
        'delete' => 'حذف',
        'confirm_delete' => 'هل أنت متأكد من حذف الفاتورة؟ سيتم إرجاع البضاعة للمخزن، تعديل رصيد العميل، وحذفها من كشف الحساب والخزينة.',
        'lang_switch' => 'English',
        'filter' => 'تصفية النتائج',
        'status' => 'الحالة',
        'all' => 'كل الحالات',
        'paid_status' => 'مدفوعة',
        'partial_status' => 'جزئية',
        'unpaid_status' => 'غير مدفوعة',
        'period_profit' => 'أرباح الفترة',
        'period_cash' => 'كاش الفترة',
    ]
];
$t = $L[$lang];

// CSRF Protection
if (empty($_SESSION['_csrf_token'])) {
    $_SESSION['_csrf_token'] = bin2hex(random_bytes(24));
}
$csrf = $_SESSION['_csrf_token'];

$today = date('Y-m-d');
$from = $_GET['from'] ?? $today;
$to = $_GET['to'] ?? $today;
$search = trim($_GET['search'] ?? '');
$status = $_GET['status'] ?? 'all';

// Pagination logic
$page = max(1, (int)($_GET['page'] ?? 1));
$perPage = 25;
$offset = ($page - 1) * $perPage;

// ==========================================
// 🚨 منطق الحذف المطور (يحل مشكلة كشف الحساب)
// ==========================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'delete') {
    if (hash_equals($_SESSION['_csrf_token'], $_POST['_token'] ?? '')) {
        $delId = (int)($_POST['id'] ?? 0);
        if ($delId > 0) {
            try {
                $pdo->beginTransaction();
                
                // 1. جلب بيانات الفاتورة قبل الحذف لمعرفة أثرها المالي
                $stmt = $pdo->prepare("SELECT * FROM sales WHERE id = ?");
                $stmt->execute([$delId]);
                $sale = $stmt->fetch(PDO::FETCH_ASSOC);

                if ($sale) {
                    $invoice_no = $sale['invoice_no'];
                    $customer_id = $sale['customer_id'];
                    $total_amount = (float)$sale['total'];
                    $paid_amount = (float)$sale['paid'];
                    $due_amount = round($total_amount - $paid_amount, 2);

                    // 2. إرجاع المخزون (إضافة الكميات المباعة للمخزن مرة أخرى)
                    $items_stmt = $pdo->prepare("SELECT product_id, qty FROM sale_items WHERE sale_id = ?");
                    $items_stmt->execute([$delId]);
                    $items = $items_stmt->fetchAll();
                    foreach ($items as $it) {
                        $pdo->prepare("UPDATE products SET stock = stock + ? WHERE id = ?")
                            ->execute([$it['qty'], $it['product_id']]);
                    }

                    // 3. عكس رصيد العميل (طرح الدين الذي تسبب به الفاتورة من حسابه)
                    if ($customer_id && $due_amount != 0) {
                        $pdo->prepare("UPDATE customers SET balance = balance - ? WHERE id = ?")
                            ->execute([$due_amount, $customer_id]);
                    }

                    // 4. حذف سجلات كشف الحساب (customer_transactions) المرتبطة بالفاتورة
                    $pdo->prepare("DELETE FROM customer_transactions WHERE note LIKE ? OR note LIKE ?")
                        ->execute(["%$invoice_no%", "Invoice #$invoice_no%"]);

                    // 5. حذف حركة الخزينة المرتبطة (cash_transactions)
                    $pdo->prepare("DELETE FROM cash_transactions WHERE sale_id = ? OR description LIKE ?")
                        ->execute([$delId, "%$invoice_no%"]);

                    // 6. حذف الأصناف والفاتورة نفسها نهائياً
                    $pdo->prepare("DELETE FROM sale_items WHERE sale_id = ?")->execute([$delId]);
                    $pdo->prepare("DELETE FROM sales WHERE id = ?")->execute([$delId]);
                }

                $pdo->commit();
                header('Location: sales_list.php?' . http_build_query($_GET));
                exit;
            } catch (Exception $e) { 
                if($pdo->inTransaction()) $pdo->rollBack(); 
                die("Error: " . $e->getMessage());
            }
        }
    }
}

// بناء شروط الفلترة
$where = "WHERE DATE(s.created_at) BETWEEN ? AND ?";
$params = [$from, $to];

if ($search !== '') {
    $where .= " AND (s.invoice_no LIKE ? OR c.name LIKE ?)";
    $params[] = "%$search%"; $params[] = "%$search%";
}
if ($status !== 'all') {
    if ($status === 'paid') $where .= " AND s.paid >= s.total";
    elseif ($status === 'partial') $where .= " AND s.paid > 0 AND s.paid < s.total";
    elseif ($status === 'unpaid') $where .= " AND s.paid = 0";
}

// جلب البيانات
$mainSql = "SELECT s.*, c.name AS customer_name, 
            (SELECT SUM(si.qty * p.cost) FROM sale_items si JOIN products p ON p.id = si.product_id WHERE si.sale_id = s.id) AS cost_sum
            FROM sales s
            LEFT JOIN customers c ON c.id = s.customer_id
            $where
            GROUP BY s.id ORDER BY s.created_at DESC LIMIT $perPage OFFSET $offset";
$stmt = $pdo->prepare($mainSql); $stmt->execute($params);
$sales = $stmt->fetchAll(PDO::FETCH_ASSOC);

// حساب إحصائيات الفترة
$total_sales = $total_paid = $total_due = $total_profit = $total_cash = 0.0;
$statsSql = "SELECT s.total, s.paid, s.payment_method, 
             (SELECT SUM(si2.qty * p2.cost) FROM sale_items si2 JOIN products p2 ON p2.id = si2.product_id WHERE si2.sale_id = s.id) as cost_total
             FROM sales s
             LEFT JOIN customers c ON c.id = s.customer_id $where";
$stmtStats = $pdo->prepare($statsSql); $stmtStats->execute($params);
$allStatsRows = $stmtStats->fetchAll(PDO::FETCH_ASSOC);

foreach ($allStatsRows as $row) {
    $total_sales += (float)$row['total'];
    $total_paid += (float)$row['paid'];
    $total_due += max(0, (float)$row['total'] - (float)$row['paid']);
    $total_profit += ((float)$row['total'] - (float)($row['cost_total'] ?? 0));
    if (strtolower($row['payment_method'] ?? '') === 'cash') $total_cash += (float)$row['paid'];
}

$totalRows = count($allStatsRows);
$totalPages = (int)ceil($totalRows / $perPage);

function build_qs($overrides = []) { return http_build_query(array_merge($_GET, $overrides)); }
function esc($v){ return htmlspecialchars($v ?? '', ENT_QUOTES, 'UTF-8'); }
?>
<!doctype html>
<html lang="<?= $lang ?>" dir="<?= $is_ar ? 'rtl' : 'ltr' ?>">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <title><?= $t['title'] ?></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">
    <style>
        :root { --primary: #2563eb; --success: #10b981; --danger: #f43f5e; --bg: #f8fafc; --border: #e2e8f0; }
        body { font-family: <?= $is_ar ? "'Cairo', sans-serif" : "'Plus Jakarta Sans', sans-serif" ?>; background-color: var(--bg); color: #1e293b; padding-bottom: 50px; }
        .bg-pattern { position: fixed; top: 0; left: 0; width: 100%; height: 100%; z-index: -1; background-image: radial-gradient(#e2e8f0 1.5px, transparent 1.5px); background-size: 40px 40px; opacity: 0.6; }
        .container-pro { max-width: 1400px; padding: 30px; margin: auto; }
        .stat-card { background: #fff; border-radius: 20px; padding: 25px; border: 1px solid var(--border); box-shadow: 0 4px 15px rgba(0,0,0,0.02); display: flex; align-items: center; gap: 20px; transition: transform 0.3s; }
        .stat-card:hover { transform: translateY(-5px); }
        .stat-icon { width: 54px; height: 54px; border-radius: 15px; display: flex; align-items: center; justify-content: center; font-size: 1.4rem; }
        .glass-card { background: #fff; border-radius: 28px; border: 1px solid var(--border); box-shadow: 0 10px 40px -10px rgba(0,0,0,0.05); overflow: hidden; margin-bottom: 30px; }
        .badge-status { padding: 5px 12px; border-radius: 50px; font-size: 0.75rem; font-weight: 700; }
        .bg-paid { background: #f0fdf4; color: #16a34a; }
        .bg-partial { background: #fffbeb; color: #d97706; }
        .bg-unpaid { background: #fef2f2; color: #dc2626; }
        .btn-action { width: 38px; height: 38px; border-radius: 10px; display: inline-flex; align-items: center; justify-content: center; transition: 0.2s; border: 1.5px solid var(--border); background: #fff; color: #64748b; text-decoration: none; margin: 0 2px; }
        .btn-action:hover { background: var(--primary); color: #fff; border-color: var(--primary); transform: translateY(-2px); }
        .btn-edit-action:hover { background: #f59e0b; border-color: #f59e0b; }
        .btn-print-action:hover { background: #6366f1; border-color: #6366f1; }
        .btn-delete:hover { background: var(--danger); border-color: var(--danger); color: white; }
        .table thead th { background: #f8fafc; color: #64748b; font-size: 0.75rem; text-transform: uppercase; padding: 20px; font-weight: 800; border: 0; }
        .table tbody td { padding: 20px; vertical-align: middle; border-bottom: 1px solid #f1f5f9; }
        .pagination .page-link { border-radius: 10px; margin: 0 3px; border: 1px solid var(--border); color: #64748b; font-weight: 700; }
        .pagination .page-item.active .page-link { background: var(--primary); border-color: var(--primary); color: white; }
    </style>
</head>
<body>

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

    <div class="container-pro">
        <!-- Header -->
        <div class="d-flex justify-content-between align-items-center mb-5">
            <div>
                <h1 class="fw-800 fs-2 m-0 text-dark"><?= $t['title'] ?></h1>
                <p class="text-muted small m-0 fw-600"><?= $is_ar ? 'إدارة المبيعات والتحليل المالي والتحكم الكامل بالسجلات' : 'Sales management, finance, and record auditing' ?></p>
            </div>
            <div class="d-flex gap-2">
                <a href="index.php" class="btn btn-light rounded-pill px-4 fw-bold border shadow-sm">🏠</a>
                <a href="sales_create.php" class="btn btn-primary rounded-pill px-4 fw-bold shadow">+ <?= $t['new_sale'] ?></a>
                <a href="?lang=<?= $is_ar ? 'en' : 'ar' ?>" class="btn btn-light rounded-pill px-4 fw-bold shadow-sm"><?= $t['lang_switch'] ?></a>
            </div>
        </div>

        <!-- Dashboard Stats -->
        <div class="row g-4 mb-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 fw-bold uppercase"><?= $t['total_sales'] ?></div><div class="fw-800 fs-4"><?= number_format($total_sales,2) ?></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 fw-bold uppercase"><?= $t['period_profit'] ?></div><div class="fw-800 fs-4 text-success"><?= number_format($total_profit,2) ?></div></div></div></div>
            <div class="col-md-3"><div class="stat-card"><div class="stat-icon" style="background:#fffbeb;color:#f59e0b;">🏧</div><div><div class="text-muted small fw-bold uppercase"><?= $t['period_cash'] ?></div><div class="fw-800 fs-4"><?= number_format($total_cash,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 fw-bold uppercase"><?= $t['total_due'] ?></div><div class="fw-800 fs-4 text-danger"><?= number_format($total_due,2) ?></div></div></div></div>
        </div>

        <!-- Filter Area -->
        <div class="glass-card">
            <div class="p-4 border-bottom bg-light">
                <form method="get" class="row g-3 align-items-end">
                    <div class="col-md-3"><label class="small fw-800 text-muted mb-1"><?= $t['search'] ?></label><input type="text" name="search" value="<?= esc($search) ?>" class="form-control rounded-3 border-2"></div>
                    <div class="col-md-2"><label class="small fw-800 text-muted mb-1"><?= $t['from'] ?></label><input type="date" name="from" value="<?= $from ?>" class="form-control rounded-3 border-2"></div>
                    <div class="col-md-2"><label class="small fw-800 text-muted mb-1"><?= $t['to'] ?></label><input type="date" name="to" value="<?= $to ?>" class="form-control rounded-3 border-2"></div>
                    <div class="col-md-2"><label class="small fw-800 text-muted mb-1"><?= $t['status'] ?></label>
                        <select name="status" class="form-select rounded-3 border-2">
                            <option value="all"><?= $t['all'] ?></option>
                            <option value="paid" <?= $status==='paid'?'selected':'' ?>><?= $t['paid_status'] ?></option>
                            <option value="partial" <?= $status==='partial'?'selected':'' ?>><?= $t['partial_status'] ?></option>
                            <option value="unpaid" <?= $status==='unpaid'?'selected':'' ?>><?= $t['unpaid_status'] ?></option>
                        </select>
                    </div>
                    <div class="col-md-3"><button type="submit" class="btn btn-primary rounded-pill w-100 fw-bold py-2"><?= $t['filter'] ?></button></div>
                </form>
            </div>

            <div class="table-responsive">
                <table class="table">
                    <thead>
                        <tr>
                            <th>#</th>
                            <th><?= $t['invoice'] ?></th>
                            <th><?= $t['customer'] ?></th>
                            <th><?= $t['total'] ?></th>
                            <th><?= $t['paid'] ?></th>
                            <th><?= $t['due'] ?></th>
                            <th><?= $t['profit'] ?></th>
                            <th><?= $t['status'] ?></th>
                            <th><?= $t['date'] ?></th>
                            <th class="text-center"><?= $t['actions'] ?></th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if(empty($sales)): ?>
                            <tr><td colspan="10" class="text-center py-5 text-muted fw-bold"><?= $t['no_sales'] ?></td></tr>
                        <?php else: foreach($sales as $i => $s): 
                            $due = max(0, $s['total'] - $s['paid']);
                            $profit = (float)$s['total'] - (float)($s['cost_sum'] ?? 0);
                            $stClass = ($s['paid'] >= $s['total']) ? 'bg-paid' : ($s['paid'] > 0 ? 'bg-partial' : 'bg-unpaid');
                            $stLabel = ($s['paid'] >= $s['total']) ? $t['paid_status'] : ($s['paid'] > 0 ? $t['partial_status'] : $t['unpaid_status']);
                        ?>
                        <tr>
                            <td class="text-muted small"><?= $offset + $i + 1 ?></td>
                            <td class="fw-800 text-primary">#<?= esc($s['invoice_no']) ?></td>
                            <td><div class="fw-700"><?= esc($s['customer_name'] ?: ($is_ar ? 'عميل نقدي' : 'Walk-in')) ?></div></td>
                            <td class="fw-800"><?= number_format($s['total'], 2) ?></td>
                            <td class="text-success fw-700"><?= number_format($s['paid'], 2) ?></td>
                            <td class="<?= $due > 0.01 ? 'text-danger fw-800' : 'text-muted' ?>"><?= number_format($due, 2) ?></td>
                            <td class="text-success fw-700"><?= number_format($profit, 2) ?></td>
                            <td><span class="badge-status <?= $stClass ?>"><?= $stLabel ?></span></td>
                            <td class="text-muted small"><?= date('M d, H:i', strtotime($s['created_at'])) ?></td>
                            <td class="text-center">
                                <div class="d-flex justify-content-center align-items-center">
                                    <!-- View Action -->
                                    <a href="sale_view.php?id=<?= $s['id'] ?>" class="btn-action" title="<?= $t['view'] ?>">
                                        <svg width="18" height="18" fill="none" stroke="currentColor" stroke-width="2.5" viewBox="0 0 24 24"><path d="M15 12a3 3 0 11-6 0 3 3 0 016 0zM2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"></path></svg>
                                    </a>
                                    <!-- Edit Action -->
                                    <a href="sales_create.php?id=<?= $s['id'] ?>" class="btn-action btn-edit-action" title="<?= $t['edit'] ?>">
                                        <svg width="18" height="18" fill="none" stroke="currentColor" stroke-width="2.5" viewBox="0 0 24 24"><path d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"></path></svg>
                                    </a>
                                    <!-- Print Action -->
                                    <a href="sales_print.php?id=<?= $s['id'] ?>" class="btn-action btn-print-action" target="_blank" title="<?= $t['print'] ?>">
                                        <svg width="18" height="18" fill="none" stroke="currentColor" stroke-width="2.5" viewBox="0 0 24 24"><path d="M17 17h2a2 2 0 002-2v-4a2 2 0 00-2-2H5a2 2 0 00-2 2v4a2 2 0 002 2h2m2 4h6a2 2 0 002-2v-4a2 2 0 00-2-2H9a2 2 0 00-2 2v4a2 2 0 002 2zm8-12V5a2 2 0 00-2-2H9a2 2 0 00-2 2v4h10z"></path></svg>
                                    </a>
                                    <!-- Delete Action -->
                                    <form method="post" onsubmit="return confirm('<?= $t['confirm_delete'] ?>')" class="d-inline">
                                        <input type="hidden" name="action" value="delete">
                                        <input type="hidden" name="id" value="<?= $s['id'] ?>">
                                        <input type="hidden" name="_token" value="<?= $csrf ?>">
                                        <button class="btn-action btn-delete" title="<?= $t['delete'] ?>">
                                            <svg width="18" height="18" fill="none" stroke="currentColor" stroke-width="2.5" viewBox="0 0 24 24"><path d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"></path></svg>
                                        </button>
                                    </form>
                                </div>
                            </td>
                        </tr>
                        <?php endforeach; endif; ?>
                    </tbody>
                </table>
            </div>
        </div>

        <?php if($totalPages > 1): ?>
        <nav><ul class="pagination justify-content-center">
            <?php for($p=1;$p<=$totalPages;$p++): ?>
                <li class="page-item <?= $p===$page? 'active':'' ?>"><a class="page-link shadow-sm" href="?<?= build_qs(['page'=>$p]) ?>"><?= $p ?></a></li>
            <?php endfor; ?>
        </ul></nav>
        <?php endif; ?>
    </div>
</body>
</html>