<?php
$pageTitle = 'تقرير المشتريات حسب المورد';
include __DIR__ . '/../../includes/header.php';

// التحقق من الصلاحيات
checkLogin();
if (!hasPermission('view_purchase_reports')) {
    header('Location: ' . SITE_URL . '/pages/errors/access_denied.php');
    exit();
}

$db = getDB();

$start_date = $_GET['start_date'] ?? date('Y-m-01');
$end_date = $_GET['end_date'] ?? date('Y-m-t');
$supplier_id = $_GET['supplier_id'] ?? '';

$sql = "SELECT s.full_name as supplier_name, 
               COUNT(pi.id) as total_invoices,
               SUM(pi.total_amount) as total_purchases
        FROM purchase_invoices pi
        JOIN suppliers s ON pi.supplier_id = s.id
        WHERE pi.invoice_date BETWEEN ? AND ?";

$params = [$start_date, $end_date];

if (!empty($supplier_id)) {
    $sql .= " AND pi.supplier_id = ?";
    $params[] = $supplier_id;
}

$sql .= " GROUP BY s.id, s.full_name ORDER BY total_purchases DESC";

$purchase_data = $db->select($sql, $params);

// جلب الموردين لعرضهم في قائمة الفلترة
$suppliers = $db->select("SELECT id, full_name FROM suppliers ORDER BY full_name ASC");

$total_purchases_amount = $db->selectOne("SELECT SUM(total_amount) as total FROM purchase_invoices WHERE invoice_date BETWEEN ? AND ?", [$start_date, $end_date])['total'] ?? 0;
$total_invoices = $db->selectOne("SELECT COUNT(*) as count FROM purchase_invoices WHERE invoice_date BETWEEN ? AND ?", [$start_date, $end_date])['count'] ?? 0;

?>

<div class="container-fluid">
    <div class="row">
        <div class="col-lg-12">
            <div class="card">
                <div class="card-header">
                    <h3 class="card-title"><?php echo $pageTitle; ?></h3>
                </div>
                <div class="card-body">
                    <form action="" method="GET" class="row g-3 align-items-center mb-4">
                        <div class="col-md-3">
                            <label for="start_date" class="form-label">تاريخ البدء:</label>
                            <input type="date" class="form-control" id="start_date" name="start_date" value="<?php echo htmlspecialchars($start_date); ?>">
                        </div>
                        <div class="col-md-3">
                            <label for="end_date" class="form-label">تاريخ الانتهاء:</label>
                            <input type="date" class="form-control" id="end_date" name="end_date" value="<?php echo htmlspecialchars($end_date); ?>">
                        </div>
                        <div class="col-md-3">
                            <label for="supplier_id" class="form-label">المورد:</label>
                            <select class="form-select" id="supplier_id" name="supplier_id">
                                <option value="">جميع الموردين</option>
                                <?php foreach ($suppliers as $supplier): ?>
                                    <option value="<?php echo $supplier['id']; ?>" <?php echo ($supplier_id == $supplier['id']) ? 'selected' : ''; ?>>
                                        <?php echo htmlspecialchars($supplier['full_name']); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-md-3">
                            <button type="submit" class="btn btn-primary mt-4">
                                <i class="fas fa-filter me-2"></i>تصفية التقرير
                            </button>
                        </div>
                    </form>

                    <div class="row mb-4">
                        <div class="col-md-6">
                            <div class="card bg-light mb-3">
                                <div class="card-body">
                                    <h5 class="card-title">إجمالي المشتريات</h5>
                                    <p class="card-text fs-4">SAR <?php echo number_format($total_purchases_amount, 2); ?></p>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="card bg-light mb-3">
                                <div class="card-body">
                                    <h5 class="card-title">عدد الفواتير</h5>
                                    <p class="card-text fs-4"><?php echo $total_invoices; ?></p>
                                </div>
                            </div>
                        </div>
                    </div>

                    <?php if (empty($purchase_data)): ?>
                        <div class="alert alert-info text-center" role="alert">
                            لا توجد بيانات مشتريات للفترة المحددة.
                        </div>
                    <?php else: ?>
                        <div class="table-responsive">
                            <table class="table table-hover table-striped">
                                <thead>
                                    <tr>
                                        <th>اسم المورد</th>
                                        <th>عدد الفواتير</th>
                                        <th>إجمالي المشتريات</th>
                                        <th>النسبة المئوية</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($purchase_data as $data): ?>
                                        <tr>
                                            <td><?php echo htmlspecialchars($data['supplier_name']); ?></td>
                                            <td><?php echo htmlspecialchars($data['total_invoices']); ?></td>
                                            <td>SAR <?php echo htmlspecialchars(number_format($data['total_purchases'], 2)); ?></td>
                                            <td>
                                                <?php 
                                                $percentage = $total_purchases_amount > 0 ? ($data['total_purchases'] / $total_purchases_amount) * 100 : 0;
                                                echo number_format($percentage, 1) . '%';
                                                ?>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    <?php endif; ?>

                    <div class="mt-4">
                        <a href="<?php echo SITE_URL; ?>/pages/reports/index.php" class="btn btn-secondary">
                            <i class="fas fa-arrow-left me-2"></i>العودة للتقارير
                        </a>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<?php include __DIR__ . '/../../includes/footer.php'; ?>



