<?php
// sales.php - سجل المبيعات الاحترافي (فلتر تاريخ، تنقل سريع، إحصائيات، تصدير)
require_once __DIR__ . '/config/db.php';
require_once __DIR__ . '/src/auth.php';
require_login();

date_default_timezone_set('Asia/Beirut');

// --- 1. إعدادات اللغة والجلسة ---
if (session_status() === PHP_SESSION_NONE) session_start();
if (isset($_GET['lang'])) $_SESSION['lang'] = $_GET['lang'] === 'ar' ? 'ar' : 'en';
$lang = $_SESSION['lang'] ?? 'en'; 
$is_ar = ($lang === 'ar');
$is_admin = true;

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

/* ====================================================================================
   المنطق البرمجي (Backend Logic)
   ==================================================================================== */

// 2. AJAX: تفاصيل الفاتورة
if (isset($_GET['action']) && $_GET['action'] === 'get_details') {
    $sale_id = intval($_GET['id'] ?? 0);
    $stmt = $pdo->prepare("
        SELECT si.*, COALESCE(NULLIF(p.name_en,''), p.name_ar, 'Deleted Product') as product_name, p.sku
        FROM sale_items si LEFT JOIN products p ON si.product_id = p.id WHERE si.sale_id = ?
    ");
    $stmt->execute([$sale_id]);
    header('Content-Type: application/json');
    echo json_encode(['success' => true, 'items' => $stmt->fetchAll(PDO::FETCH_ASSOC)]);
    exit;
}

// 3. معالجة الحذف
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_item_id'])) {
    $item_id = intval($_POST['delete_item_id']);
    try {
        $pdo->beginTransaction();
        $stmt = $pdo->prepare("SELECT si.*, s.customer_id, s.invoice_no FROM sale_items si JOIN sales s ON si.sale_id = s.id WHERE si.id = ? LIMIT 1");
        $stmt->execute([$item_id]);
        $item = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($item) {
            $sale_id = $item['sale_id'];
            $qty = floatval($item['qty']);
            $subtotal = floatval($item['subtotal']);
            $prod_id = $item['product_id'];
            $cust_id = $item['customer_id'];
            
            // إرجاع المخزون وتصحيح الحسابات
            $pdo->prepare("UPDATE products SET stock = stock + ? WHERE id = ?")->execute([$qty, $prod_id]);
            if ($cust_id) $pdo->prepare("UPDATE customers SET balance = balance - ? WHERE id = ?")->execute([$subtotal, $cust_id]);
            
            $cost = $pdo->query("SELECT COALESCE(cost, 0) FROM products WHERE id = $prod_id")->fetchColumn();
            $profit_deduct = ($item['unit_price'] - $cost) * $qty;
            $pdo->prepare("UPDATE sales SET total = total - ?, profit = profit - ? WHERE id = ?")->execute([$subtotal, $profit_deduct, $sale_id]);
            
            $pdo->prepare("DELETE FROM sale_items WHERE id = ?")->execute([$item_id]);
            
            if ($pdo->query("SELECT COUNT(*) FROM sale_items WHERE sale_id = $sale_id")->fetchColumn() == 0) {
                if ($cust_id) $pdo->prepare("DELETE FROM customer_transactions WHERE customer_id = ? AND note LIKE ?")->execute([$cust_id, "%{$item['invoice_no']}%"]);
                $pdo->prepare("DELETE FROM cash_transactions WHERE sale_id = ?")->execute([$sale_id]);
                $pdo->prepare("DELETE FROM sales WHERE id = ?")->execute([$sale_id]);
            }
            $msg = $is_ar ? '✅ تم حذف المنتج وتصحيح الحسابات' : '✅ Item deleted and accounts updated';
            $msg_type = 'success';
        }
        $pdo->commit();
    } catch (Exception $e) {
        if($pdo->inTransaction()) $pdo->rollBack();
        $msg = '❌ Error: ' . $e->getMessage(); $msg_type = 'danger';
    }
}

// 4. إعداد الفلتر والتواريخ
$search = trim($_GET['q'] ?? '');

if (!isset($_GET['date_from'])) {
    $date_from = date('Y-m-d');
    $date_to = date('Y-m-d');
} else {
    $date_from = $_GET['date_from'];
    $date_to = $_GET['date_to'];
}

// --- منطق التنقل السريع بين الأيام ---
$current_date_ref = !empty($date_from) ? $date_from : date('Y-m-d');
$prev_day = date('Y-m-d', strtotime($current_date_ref . ' -1 day'));
$next_day = date('Y-m-d', strtotime($current_date_ref . ' +1 day'));
$today_day = date('Y-m-d');

// بناء روابط التنقل مع الحفاظ على البحث والحدود
$base_params = $_GET; 
unset($base_params['date_from'], $base_params['date_to'], $base_params['page']);

$url_prev = '?' . http_build_query(array_merge($base_params, ['date_from'=>$prev_day, 'date_to'=>$prev_day]));
$url_next = '?' . http_build_query(array_merge($base_params, ['date_from'=>$next_day, 'date_to'=>$next_day]));
$url_today = '?' . http_build_query(array_merge($base_params, ['date_from'=>$today_day, 'date_to'=>$today_day]));
// ------------------------------------

$limit = isset($_GET['limit']) ? intval($_GET['limit']) : 25;
$page = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
$offset = ($page - 1) * $limit;

$where = "1=1";
$params = [];

if ($search !== '') {
    $where .= " AND (s.invoice_no LIKE ? OR p.name_en LIKE ? OR p.name_ar LIKE ? OR p.sku LIKE ? OR c.name LIKE ?)";
    $sp = "%$search%";
    $params = array_merge($params, [$sp, $sp, $sp, $sp, $sp]);
}
if ($date_from !== '') {
    $where .= " AND DATE(s.created_at) >= ?";
    $params[] = $date_from;
}
if ($date_to !== '') {
    $where .= " AND DATE(s.created_at) <= ?";
    $params[] = $date_to;
}

// 5. تصدير Excel
if (isset($_GET['export']) && $_GET['export'] == '1') {
    $sql = "SELECT s.invoice_no, s.created_at, c.name as customer, 
                   COALESCE(NULLIF(p.name_en,''), p.name_ar) as product, 
                   si.qty, si.unit_price, si.subtotal
            FROM sale_items si
            JOIN sales s ON si.sale_id = s.id
            LEFT JOIN products p ON si.product_id = p.id
            LEFT JOIN customers c ON s.customer_id = c.id
            WHERE $where ORDER BY s.created_at DESC";
    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    
    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename=Sales_Report_' . date('Y-m-d') . '.csv');
    $output = fopen('php://output', 'w');
    fprintf($output, chr(0xEF).chr(0xBB).chr(0xBF));
    fputcsv($output, ['Invoice', 'Date', 'Customer', 'Product', 'Qty', 'Price', 'Total']);
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) fputcsv($output, $row);
    fclose($output);
    exit;
}

// 6. الإحصائيات
$statsSql = "SELECT 
                COUNT(*) as count,
                COALESCE(SUM(si.qty), 0) as total_qty, 
                COALESCE(SUM(si.subtotal), 0) as total_sales,
                COALESCE(SUM( (si.unit_price - COALESCE(p.cost,0)) * si.qty ), 0) as total_profit
             FROM sale_items si
             JOIN sales s ON si.sale_id = s.id
             LEFT JOIN products p ON si.product_id = p.id
             LEFT JOIN customers c ON s.customer_id = c.id
             WHERE $where";
$statsStmt = $pdo->prepare($statsSql);
$statsStmt->execute($params);
$stats = $statsStmt->fetch(PDO::FETCH_ASSOC);

// 7. جلب البيانات
$sql = "SELECT si.*, s.invoice_no, s.created_at, s.id as sale_id, c.name as customer_name,
               COALESCE(NULLIF(p.name_en,''), p.name_ar, 'Deleted') as product_name, p.sku,
               COALESCE(p.cost, 0) as product_cost
        FROM sale_items si
        JOIN sales s ON si.sale_id = s.id
        LEFT JOIN products p ON si.product_id = p.id
        LEFT JOIN customers c ON s.customer_id = c.id
        WHERE $where ORDER BY s.created_at DESC LIMIT $limit OFFSET $offset";
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$sold_items = $stmt->fetchAll(PDO::FETCH_ASSOC);

$total_pages = ceil($stats['count'] / $limit);
?>
<!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><?= $is_ar ? 'تقرير المبيعات اليومي' : 'Daily Sales Report' ?></title>
    <link href="https://fonts.googleapis.com/css2?family=Cairo:wght@400;600;700&family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css" rel="stylesheet">
    <style>
        :root { --primary: #4338ca; --bg: #f8fafc; --border: #e2e8f0; }
        body { background-color: var(--bg); font-family: <?= $is_ar ? "'Cairo', sans-serif" : "'Inter', sans-serif" ?>; color: #334155; }
        .top-nav { background: #fff; padding: 0.8rem 1.5rem; border-bottom: 1px solid var(--border); display: flex; justify-content: space-between; align-items: center; }
        
        .filter-card { background: #fff; border-radius: 12px; border: 1px solid var(--border); padding: 1.5rem; margin-bottom: 1.5rem; box-shadow: 0 2px 4px rgba(0,0,0,0.02); }
        .stats-box { background: #fff; border: 1px solid var(--border); border-radius: 10px; padding: 1rem; text-align: center; height: 100%; transition: transform 0.2s; }
        .stats-box:hover { transform: translateY(-3px); box-shadow: 0 4px 6px -1px rgba(0,0,0,0.1); }
        .stats-label { color: #64748b; font-size: 0.85rem; font-weight: 600; text-transform: uppercase; letter-spacing: 0.5px; }
        .stats-val { font-size: 1.5rem; font-weight: 700; color: #1e293b; margin-top: 5px; }
        .text-profit { color: #10b981; }

        .table-card { background: #fff; border-radius: 12px; border: 1px solid var(--border); overflow: hidden; box-shadow: 0 4px 6px -1px rgba(0,0,0,0.05); }
        .table thead th { background: #f1f5f9; color: #475569; font-weight: 600; font-size: 0.8rem; text-transform: uppercase; padding: 1rem; border-bottom: 2px solid var(--border); }
        .table tbody td { padding: 1rem; vertical-align: middle; border-bottom: 1px solid #f1f5f9; font-size: 0.95rem; }
        .sku-tag { background: #f1f5f9; padding: 2px 6px; border-radius: 4px; font-size: 0.75rem; color: #64748b; font-family: monospace; }
        
        .btn-icon { width: 32px; height: 32px; display: inline-flex; align-items: center; justify-content: center; border-radius: 6px; border: 1px solid #cbd5e1; color: #64748b; background: white; transition: all 0.2s; }
        .btn-icon:hover { background: #f8fafc; color: var(--primary); border-color: var(--primary); }
        .btn-delete:hover { background: #fee2e2; color: #ef4444; border-color: #ef4444; }
        
        .nav-btn-group .btn { min-width: 100px; font-weight: 600; }
    </style>
</head>
<body>

    <nav class="top-nav">
        <div class="fw-bold text-primary fs-5"><i class="fa fa-chart-pie me-2"></i> <?= $is_ar ? 'تقرير المبيعات' : 'Sales Report' ?></div>
        <div class="d-flex gap-2">
            <a href="index.php" class="btn btn-light btn-sm border">🏠</a>
            <a href="sales_create.php" class="btn btn-primary btn-sm px-3 fw-bold">+ <?= $is_ar ? 'بيع جديد' : 'New Sale' ?></a>
            <a href="?lang=<?= $is_ar ? 'en' : 'ar' ?>" class="btn btn-outline-secondary btn-sm fw-bold"><?= $is_ar ? 'EN' : 'عربي' ?></a>
        </div>
    </nav>

    <div class="container-fluid px-4 py-4">
        <?php if (isset($msg)): ?>
            <script>document.addEventListener('DOMContentLoaded', ()=> Swal.fire({icon: '<?= $msg_type ?>', title: '<?= $msg ?>', toast: true, position: 'top-end', showConfirmButton: false, timer: 3000}));</script>
        <?php endif; ?>

        <!-- الفلتر -->
        <div class="filter-card">
            
            <!-- أزرار التنقل السريع بين الأيام -->
            <div class="d-flex justify-content-center mb-3 nav-btn-group gap-2">
                <a href="<?= $url_prev ?>" class="btn btn-outline-primary btn-sm rounded-pill">
                    <i class="fa <?= $is_ar ? 'fa-chevron-right' : 'fa-chevron-left' ?>"></i> <?= $is_ar ? 'السابق' : 'Prev Day' ?>
                </a>
                <a href="<?= $url_today ?>" class="btn btn-outline-secondary btn-sm rounded-pill">
                    <?= $is_ar ? 'اليوم' : 'Today' ?>
                </a>
                <a href="<?= $url_next ?>" class="btn btn-outline-primary btn-sm rounded-pill">
                     <?= $is_ar ? 'التالي' : 'Next Day' ?> <i class="fa <?= $is_ar ? 'fa-chevron-left' : 'fa-chevron-right' ?>"></i>
                </a>
            </div>

            <form method="GET" class="row g-3 align-items-end">
                <input type="hidden" name="lang" value="<?= $lang ?>">
                
                <div class="col-md-3">
                    <label class="form-label small fw-bold text-muted"><?= $is_ar ? 'بحث شامل' : 'Search' ?></label>
                    <input type="text" name="q" class="form-control" placeholder="..." value="<?= esc($search) ?>">
                </div>
                
                <div class="col-md-2 col-6">
                    <label class="form-label small fw-bold text-muted"><?= $is_ar ? 'من تاريخ' : 'Date From' ?></label>
                    <input type="date" name="date_from" class="form-control" value="<?= esc($date_from) ?>">
                </div>
                
                <div class="col-md-2 col-6">
                    <label class="form-label small fw-bold text-muted"><?= $is_ar ? 'إلى تاريخ' : 'Date To' ?></label>
                    <input type="date" name="date_to" class="form-control" value="<?= esc($date_to) ?>">
                </div>

                <div class="col-md-2 col-6">
                    <label class="form-label small fw-bold text-muted"><?= $is_ar ? 'عرض' : 'Show' ?></label>
                    <select name="limit" class="form-select">
                        <option value="10" <?= $limit==10?'selected':'' ?>>10</option>
                        <option value="25" <?= $limit==25?'selected':'' ?>>25</option>
                        <option value="50" <?= $limit==50?'selected':'' ?>>50</option>
                        <option value="100" <?= $limit==100?'selected':'' ?>>100</option>
                    </select>
                </div>

                <div class="col-md-3 d-flex gap-2">
                    <button type="submit" class="btn btn-primary flex-grow-1 fw-bold"><i class="fa fa-filter"></i> <?= $is_ar ? 'تطبيق' : 'Apply' ?></button>
                    <?php if(!empty($sold_items)): ?>
                        <button type="submit" name="export" value="1" class="btn btn-success fw-bold" title="Excel"><i class="fa fa-file-excel"></i></button>
                    <?php endif; ?>
                    <a href="sales.php?date_from=&date_to=" class="btn btn-light border" title="<?= $is_ar ? 'عرض الكل' : 'Reset' ?>"><i class="fa fa-rotate-left"></i></a>
                </div>
            </form>
        </div>

        <!-- الإحصائيات -->
        <div class="row g-3 mb-4">
            <div class="col-6 col-md-3">
                <div class="stats-box border-primary border-opacity-25 bg-primary bg-opacity-10">
                    <div class="stats-label text-primary"><?= $is_ar ? 'عمليات البيع' : 'Transactions' ?></div>
                    <div class="stats-val text-primary"><?= number_format($stats['count']) ?></div>
                </div>
            </div>
            <div class="col-6 col-md-3">
                <div class="stats-box">
                    <div class="stats-label"><?= $is_ar ? 'القطع المباعة' : 'Units Sold' ?></div>
                    <div class="stats-val"><?= number_format($stats['total_qty']) ?></div>
                </div>
            </div>
            <div class="col-6 col-md-3">
                <div class="stats-box">
                    <div class="stats-label"><?= $is_ar ? 'إجمالي المبيعات' : 'Total Revenue' ?></div>
                    <div class="stats-val text-dark"><?= number_format($stats['total_sales'], 2) ?> <small class="text-muted fs-6">$</small></div>
                </div>
            </div>
            <?php if($is_admin): ?>
            <div class="col-6 col-md-3">
                <div class="stats-box border-success border-opacity-25 bg-success bg-opacity-10">
                    <div class="stats-label text-success"><?= $is_ar ? 'صافي الربح' : 'Net Profit' ?></div>
                    <div class="stats-val text-success"><?= number_format($stats['total_profit'], 2) ?> <small class="fs-6">$</small></div>
                </div>
            </div>
            <?php endif; ?>
        </div>

        <!-- الجدول -->
        <div class="table-card">
            <div class="table-responsive">
                <table class="table table-hover mb-0">
                    <thead>
                        <tr>
                            <th><?= $is_ar ? 'الفاتورة' : 'Invoice' ?></th>
                            <th><?= $is_ar ? 'التاريخ' : 'Date' ?></th>
                            <th><?= $is_ar ? 'المنتج' : 'Product' ?></th>
                            <th><?= $is_ar ? 'العميل' : 'Customer' ?></th>
                            <th class="text-center"><?= $is_ar ? 'العدد' : 'Qty' ?></th>
                            <th class="text-center"><?= $is_ar ? 'سعر البيع' : 'Price' ?></th>
                            <th class="text-center"><?= $is_ar ? 'الإجمالي' : 'Total' ?></th>
                            <?php if($is_admin): ?><th class="text-center text-success"><?= $is_ar ? 'الربح' : 'Profit' ?></th><?php endif; ?>
                            <th class="text-end"><?= $is_ar ? 'إجراء' : 'Action' ?></th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($sold_items)): ?>
                            <tr><td colspan="9" class="text-center py-5 text-muted fw-bold"><?= $is_ar ? 'لا توجد بيانات للفترة المحددة' : 'No Data Found for this period' ?></td></tr>
                        <?php else: foreach($sold_items as $it): 
                            $profit = ($it['unit_price'] - $it['product_cost']) * $it['qty'];
                        ?>
                        <tr>
                            <td><a href="sale_view.php?id=<?= $it['sale_id'] ?>" class="fw-bold text-primary text-decoration-none">#<?= esc($it['invoice_no']) ?></a></td>
                            <td class="small text-muted"><?= date('Y-m-d H:i', strtotime($it['created_at'])) ?></td>
                            <td>
                                <div class="fw-bold text-dark"><?= esc($it['product_name']) ?></div>
                                <div class="sku-tag d-inline-block mt-1"><?= esc($it['sku']) ?></div>
                            </td>
                            <td><?= esc($it['customer_name'] ?: ($is_ar ? 'زبون نقدي' : 'Walk-in')) ?></td>
                            <td class="text-center fw-bold"><?= number_format($it['qty']) ?></td>
                            <td class="text-center"><?= number_format($it['unit_price'], 2) ?></td>
                            <td class="text-center fw-bold"><?= number_format($it['subtotal'], 2) ?></td>
                            <?php if($is_admin): ?>
                                <td class="text-center fw-bold text-profit"><?= number_format($profit, 2) ?></td>
                            <?php endif; ?>
                            <td class="text-end">
                                <div class="d-flex justify-content-end gap-1">
                                    <button class="btn-icon" onclick="viewDetails(<?= $it['sale_id'] ?>, '<?= $it['invoice_no'] ?>')"><i class="fa fa-eye"></i></button>
                                    <a href="sales_print.php?id=<?= $it['sale_id'] ?>" target="_blank" class="btn-icon"><i class="fa fa-print"></i></a>
                                    <button onclick="confirmDelete(<?= $it['id'] ?>)" class="btn-icon btn-delete"><i class="fa fa-trash"></i></button>
                                </div>
                            </td>
                        </tr>
                        <?php endforeach; endif; ?>
                    </tbody>
                </table>
            </div>

            <?php if ($total_pages > 1): ?>
            <div class="p-3 border-top bg-light d-flex justify-content-center">
                <nav>
                    <ul class="pagination pagination-sm mb-0">
                        <li class="page-item <?= $page <= 1 ? 'disabled' : '' ?>">
                            <a class="page-link" href="<?= $page > 1 ? '?page='.($page-1)."&q=$search&date_from=$date_from&date_to=$date_to&limit=$limit" : '#' ?>">&laquo;</a>
                        </li>
                        <?php for($i=1; $i<=$total_pages; $i++): ?>
                            <li class="page-item <?= $i==$page ? 'active' : '' ?>">
                                <a class="page-link" href="?page=<?= $i ?>&q=<?= $search ?>&date_from=<?= $date_from ?>&date_to=<?= $date_to ?>&limit=<?= $limit ?>"><?= $i ?></a>
                            </li>
                        <?php endfor; ?>
                        <li class="page-item <?= $page >= $total_pages ? 'disabled' : '' ?>">
                            <a class="page-link" href="<?= $page < $total_pages ? '?page='.($page+1)."&q=$search&date_from=$date_from&date_to=$date_to&limit=$limit" : '#' ?>">&raquo;</a>
                        </li>
                    </ul>
                </nav>
            </div>
            <?php endif; ?>
        </div>
    </div>

    <form id="deleteForm" method="POST" style="display:none"><input type="hidden" name="delete_item_id" id="deleteInput"></form>
    <div class="modal fade" id="detailsModal" tabindex="-1"><div class="modal-dialog modal-dialog-centered"><div class="modal-content rounded-4 border-0"><div class="modal-header border-bottom"><h6 class="modal-title fw-bold">#<span id="modalInvNo"></span></h6><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div><div class="modal-body p-4"><div id="modalLoader" class="text-center"><div class="spinner-border text-primary"></div></div><div id="modalItems"></div></div></div></div></div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <script>
        function viewDetails(id, invoiceNo) {
            const modal = new bootstrap.Modal(document.getElementById('detailsModal'));
            const itemsDiv = document.getElementById('modalItems');
            const loader = document.getElementById('modalLoader');
            document.getElementById('modalInvNo').textContent = invoiceNo;
            loader.style.display = 'block'; itemsDiv.innerHTML = ''; modal.show();
            fetch(`?action=get_details&id=${id}`).then(res => res.json()).then(data => {
                loader.style.display = 'none';
                if (data.success && data.items.length > 0) {
                    let html = '<table class="table table-sm mb-0">';
                    data.items.forEach(item => {
                        html += `<tr><td>${item.product_name}</td><td class="text-end fw-bold">${parseFloat(item.subtotal).toFixed(2)}</td></tr>`;
                    });
                    html += '</table>';
                    itemsDiv.innerHTML = html;
                }
            });
        }
        function confirmDelete(id) {
            Swal.fire({
                title: '<?= $is_ar ? "حذف؟" : "Delete?" ?>',
                text: '<?= $is_ar ? "تأكيد حذف هذا العنصر؟" : "Confirm delete item?" ?>',
                icon: 'warning', showCancelButton: true, confirmButtonColor: '#ef4444', cancelButtonColor: '#64748b'
            }).then((result) => { if (result.isConfirmed) { document.getElementById('deleteInput').value = id; document.getElementById('deleteForm').submit(); }});
        }
    </script>
</body>
</html>