<?php
session_start();
require_once 'config/db.php';

if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

$db = new Database();
$pdo = $db->getConnection();

// تحديد الفترة الزمنية للمبيعات
$period = $_GET['period'] ?? 'today';
$date_filter = '';

switch ($period) {
    case 'week':
        $date_filter = "AND date(sale_date) >= date('now', '-7 days')";
        break;
    case 'month':
        $date_filter = "AND date(sale_date) >= date('now', '-1 month')";
        break;
    case 'custom':
        $start_date = $_GET['start_date'] ?? '';
        $end_date = $_GET['end_date'] ?? '';
        if ($start_date && $end_date) {
            $date_filter = "AND date(sale_date) BETWEEN :start_date AND :end_date";
        }
        break;
    default: // today
        $date_filter = "AND date(sale_date) = date('now')";
}

try {
    // استرجاع المبيعات
    $query = "
        SELECT 
            s.id,
            p.name as product_name,
            s.quantity,
            s.price,
            (s.quantity * s.price) as total,
            s.sale_date
        FROM sales s
        JOIN products p ON p.id = s.product_id
        WHERE 1=1 $date_filter
        ORDER BY s.sale_date DESC
    ";
    
    if ($period === 'custom' && $start_date && $end_date) {
        $stmt = $pdo->prepare($query);
        $stmt->execute([
            ':start_date' => $start_date,
            ':end_date' => $end_date
        ]);
    } else {
        $stmt = $pdo->query($query);
    }
    
    $sales = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // حساب الإجماليات
    $total_sales = array_sum(array_column($sales, 'total'));
    $total_items = array_sum(array_column($sales, 'quantity'));
    
} catch (PDOException $e) {
    $error = "حدث خطأ في قاعدة البيانات: " . $e->getMessage();
}
?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>المبيعات - نظام إدارة البقالة</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.css" rel="stylesheet">
    <link href="assets/css/style.css" rel="stylesheet">
</head>
<body>

    <?php include 'includes/header.php'; ?>
    <div class="container mt-4">
        <div class="d-flex justify-content-between align-items-center mb-4">
            <h2>المبيعات</h2>
            <a href="sale_add.php" class="btn btn-primary">
                <i class="fas fa-plus"></i> تسجيل بيع جديد
            </a>
        </div>

        <!-- فلترة المبيعات -->
        <div class="card mb-4">
            <div class="card-body">
                <form method="GET" class="row g-3">
                    <div class="col-md-4">
                        <label class="form-label">الفترة الزمنية</label>
                        <select name="period" class="form-select" onchange="toggleDateInputs(this.value)">
                            <option value="today" <?php echo $period === 'today' ? 'selected' : ''; ?>>اليوم</option>
                            <option value="week" <?php echo $period === 'week' ? 'selected' : ''; ?>>آخر أسبوع</option>
                            <option value="month" <?php echo $period === 'month' ? 'selected' : ''; ?>>آخر شهر</option>
                            <option value="custom" <?php echo $period === 'custom' ? 'selected' : ''; ?>>تاريخ محدد</option>
                        </select>
                    </div>
                    <div class="col-md-3 custom-date" style="display: <?php echo $period === 'custom' ? 'block' : 'none'; ?>">
                        <label class="form-label">من تاريخ</label>
                        <input type="date" name="start_date" class="form-control" value="<?php echo $start_date ?? ''; ?>">
                    </div>
                    <div class="col-md-3 custom-date" style="display: <?php echo $period === 'custom' ? 'block' : 'none'; ?>">
                        <label class="form-label">إلى تاريخ</label>
                        <input type="date" name="end_date" class="form-control" value="<?php echo $end_date ?? ''; ?>">
                    </div>
                    <div class="col-md-2 d-flex align-items-end">
                        <button type="submit" class="btn btn-primary w-100">تطبيق</button>
                    </div>
                </form>
            </div>
        </div>

        <!-- ملخص المبيعات -->
        <div class="row mb-4">
            <div class="col-md-6">
                <div class="card bg-primary text-white">
                    <div class="card-body">
                        <h5 class="card-title">إجمالي المبيعات</h5>
                        <p class="card-text display-6"><?php echo number_format($total_sales, 2); ?> DH</p>
                    </div>
                </div>
            </div>
            <div class="col-md-6">
                <div class="card bg-success text-white">
                    <div class="card-body">
                        <h5 class="card-title">عدد المنتجات المباعة</h5>
                        <p class="card-text display-6"><?php echo $total_items; ?></p>
                    </div>
                </div>
            </div>
        </div>

        <!-- جدول المبيعات -->
        <div class="card">
            <div class="card-body">
                <?php if (isset($error)): ?>
                    <div class="alert alert-danger">
                        <?php echo htmlspecialchars($error); ?>
                    </div>
                <?php else: ?>
                    <div class="table-responsive">
                        <table class="table table-hover">
                            <thead>
                                <tr>
                                    <th>#</th>
                                    <th>المنتج</th>
                                    <th>الكمية</th>
                                    <th>السعر</th>
                                    <th>الإجمالي</th>
                                    <th>التاريخ</th>
                                    <th>الإجراءات</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($sales as $sale): ?>
                                    <tr>
                                        <td><?php echo htmlspecialchars($sale['id']); ?></td>
                                        <td><?php echo htmlspecialchars($sale['product_name']); ?></td>
                                        <td><?php echo $sale['quantity']; ?></td>
                                        <td><?php echo number_format($sale['price'], 2); ?> DH</td>
                                        <td><?php echo number_format($sale['total'], 2); ?> DH</td>
                                        <td><?php echo date('Y-m-d H:i', strtotime($sale['sale_date'])); ?></td>
                                        <td>
                                            <button type="button" class="btn btn-sm btn-danger" 
                                                    onclick="deleteSale(<?php echo $sale['id']; ?>)">
                                                حذف
                                            </button>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        function toggleDateInputs(value) {
            const customDateInputs = document.querySelectorAll('.custom-date');
            customDateInputs.forEach(input => {
                input.style.display = value === 'custom' ? 'block' : 'none';
            });
        }

        function deleteSale(saleId) {
            if (confirm('هل أنت متأكد من حذف هذا البيع؟')) {
                fetch('api/delete_sale.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({ id: saleId })
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        location.reload();
                    } else {
                        alert('حدث خطأ أثناء حذف البيع');
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('حدث خطأ أثناء حذف البيع');
                });
            }
        }
    </script>
</body>
</html>
