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

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

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

// تحديد الفترة الزمنية
$start_date = isset($_GET['start_date']) ? $_GET['start_date'] : date('Y-m-01');
$end_date = isset($_GET['end_date']) ? $_GET['end_date'] : date('Y-m-d');

// الحصول على إحصائيات المبيعات
$stmt = $pdo->prepare("
    SELECT 
        COUNT(*) as total_sales,
        COALESCE(SUM(price * quantity), 0) as total_amount,
        MIN(price * quantity) as min_sale,
        MAX(price * quantity) as max_sale,
        AVG(price * quantity) as avg_sale
    FROM sales 
    WHERE date(sale_date) BETWEEN ? AND ?
");
$stmt->execute([$start_date, $end_date]);
$sales_stats = $stmt->fetch(PDO::FETCH_ASSOC);

// الحصول على إحصائيات الديون
$stmt = $pdo->prepare("
    SELECT 
        COUNT(*) as total_debts,
        COALESCE(SUM(amount), 0) as total_debt_amount,
        COALESCE(SUM(paid), 0) as total_paid_amount
    FROM debts 
    WHERE date(date) BETWEEN ? AND ?
");
$stmt->execute([$start_date, $end_date]);
$debt_stats = $stmt->fetch(PDO::FETCH_ASSOC);

// الحصول على المنتجات الأكثر مبيعاً
$stmt = $pdo->prepare("
    SELECT 
        p.name,
        SUM(s.quantity) as total_quantity,
        SUM(s.price * s.quantity) as total_amount
    FROM sales s
    JOIN products p ON s.product_id = p.id
    WHERE date(s.sale_date) BETWEEN ? AND ?
    GROUP BY p.id, p.name
    ORDER BY total_quantity DESC
    LIMIT 5
");
$stmt->execute([$start_date, $end_date]);
$top_products = $stmt->fetchAll(PDO::FETCH_ASSOC);

// الحصول على الزبائن الأكثر مديونية
$stmt = $pdo->prepare("
    SELECT 
        c.name,
        c.phone,
        COALESCE(SUM(d.amount), 0) as total_debt,
        COALESCE(SUM(d.paid), 0) as total_paid
    FROM customers c
    LEFT JOIN debts d ON c.id = d.customer_id
    WHERE d.date BETWEEN ? AND ?
    GROUP BY c.id, c.name, c.phone
    HAVING total_debt > total_paid
    ORDER BY (total_debt - total_paid) DESC
    LIMIT 5
");
$stmt->execute([$start_date, $end_date]);
$top_debtors = $stmt->fetchAll(PDO::FETCH_ASSOC);

?>
<!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="assets/css/style.css" rel="stylesheet">
    <style>
        @media print {
            .no-print {
                display: none !important;
            }
            .card {
                border: none !important;
            }
            .container {
                width: 100% !important;
                max-width: none !important;
            }
        }
        .report-header {
            text-align: center;
            margin-bottom: 30px;
        }
        .report-header h1 {
            font-size: 24px;
            margin-bottom: 10px;
        }
        .report-period {
            font-size: 16px;
            color: #666;
            margin-bottom: 20px;
        }
    </style>
</head>
<body>
<?php include 'includes/header.php'; ?>

    <div class="container mt-4">
        <!-- نموذج اختيار الفترة -->
        <form method="GET" class="card mb-4 no-print">
            <div class="card-body">
                <div class="row">
                    <div class="col-md-4">
                        <label for="start_date" class="form-label">من تاريخ</label>
                        <input type="date" class="form-control" id="start_date" name="start_date"
                               value="<?php echo $start_date; ?>">
                    </div>
                    <div class="col-md-4">
                        <label for="end_date" class="form-label">إلى تاريخ</label>
                        <input type="date" class="form-control" id="end_date" name="end_date"
                               value="<?php echo $end_date; ?>">
                    </div>
                    <div class="col-md-4 d-flex align-items-end">
                        <button type="submit" class="btn btn-primary me-2">عرض التقرير</button>
                        <button type="button" class="btn btn-success" onclick="window.print()">
                            طباعة التقرير
                        </button>
                    </div>
                </div>
            </div>
        </form>

        <!-- رأس التقرير -->
        <div class="report-header">
            <h1>التقرير المالي</h1>
            <div class="report-period">
                الفترة من <?php echo date('Y/m/d', strtotime($start_date)); ?> 
                إلى <?php echo date('Y/m/d', strtotime($end_date)); ?>
            </div>
        </div>

        <!-- ملخص المبيعات -->
        <div class="row mb-4">
            <div class="col-md-6">
                <div class="card">
                    <div class="card-body">
                        <h5 class="card-title">ملخص المبيعات</h5>
                        <table class="table">
                            <tr>
                                <th>عدد المبيعات:</th>
                                <td><?php echo number_format($sales_stats['total_sales']); ?></td>
                            </tr>
                            <tr>
                                <th>إجمالي المبيعات:</th>
                                <td><?php echo number_format($sales_stats['total_amount'], 2); ?> DH</td>
                            </tr>
                            <tr>
                                <th>متوسط قيمة البيع:</th>
                                <td><?php echo number_format($sales_stats['avg_sale'], 2); ?> DH</td>
                            </tr>
                            <tr>
                                <th>أقل قيمة بيع:</th>
                                <td><?php echo number_format($sales_stats['min_sale'], 2); ?> DH</td>
                            </tr>
                            <tr>
                                <th>أعلى قيمة بيع:</th>
                                <td><?php echo number_format($sales_stats['max_sale'], 2); ?> DH</td>
                            </tr>
                        </table>
                    </div>
                </div>
            </div>
            <div class="col-md-6">
                <div class="card">
                    <div class="card-body">
                        <h5 class="card-title">ملخص الديون</h5>
                        <table class="table">
                            <tr>
                                <th>عدد الديون:</th>
                                <td><?php echo number_format($debt_stats['total_debts']); ?></td>
                            </tr>
                            <tr>
                                <th>إجمالي الديون:</th>
                                <td><?php echo number_format($debt_stats['total_debt_amount'], 2); ?> DH</td>
                            </tr>
                            <tr>
                                <th>إجمالي المدفوع:</th>
                                <td><?php echo number_format($debt_stats['total_paid_amount'], 2); ?> DH</td>
                            </tr>
                            <tr>
                                <th>إجمالي المتبقي:</th>
                                <td class="<?php echo ($debt_stats['total_debt_amount'] - $debt_stats['total_paid_amount']) > 0 ? 'text-danger' : 'text-success'; ?>">
                                    <?php echo number_format($debt_stats['total_debt_amount'] - $debt_stats['total_paid_amount'], 2); ?> DH
                                </td>
                            </tr>
                        </table>
                    </div>
                </div>
            </div>
        </div>

        <!-- المنتجات الأكثر مبيعاً -->
        <div class="row mb-4">
            <div class="col-md-6">
                <div class="card">
                    <div class="card-body">
                        <h5 class="card-title">المنتجات الأكثر مبيعاً</h5>
                        <div class="table-responsive">
                            <table class="table">
                                <thead>
                                    <tr>
                                        <th>المنتج</th>
                                        <th>الكمية</th>
                                        <th>المبلغ</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($top_products as $product): ?>
                                        <tr>
                                            <td><?php echo htmlspecialchars($product['name']); ?></td>
                                            <td><?php echo number_format($product['total_quantity']); ?></td>
                                            <td><?php echo number_format($product['total_amount'], 2); ?> DH</td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-md-6">
                <div class="card">
                    <div class="card-body">
                        <h5 class="card-title">الزبائن الأكثر مديونية</h5>
                        <div class="table-responsive">
                            <table class="table">
                                <thead>
                                    <tr>
                                        <th>الزبون</th>
                                        <th>رقم الهاتف</th>
                                        <th>المتبقي</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($top_debtors as $debtor): ?>
                                        <?php $remaining = $debtor['total_debt'] - $debtor['total_paid']; ?>
                                        <tr>
                                            <td><?php echo htmlspecialchars($debtor['name']); ?></td>
                                            <td><?php echo htmlspecialchars($debtor['phone']); ?></td>
                                            <td class="text-danger">
                                                <?php echo number_format($remaining, 2); ?> DH
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- توقيع التقرير -->
        <div class="row mt-5">
            <div class="col-12 text-start">
                <p>تاريخ إصدار التقرير: <?php echo date('Y/m/d H:i'); ?></p>
            </div>
        </div>
    </div>

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