<?php
session_start();

// التحقق من تسجيل الدخول
if (!isset($_SESSION['user_id'])) {
    header("Location: index.php");
    exit();
}

require_once 'db_connect.php';

// جلب قائمة الموظفين للفلتر
$employees = [];
try {
    $employees = $conn->query("SELECT id, name FROM employees")->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    error_log("Error fetching employees: " . $e->getMessage());
    $employees = [];
}

// معالجة الفلاتر
$start_date = $_GET['start_date'] ?? '';
$end_date = $_GET['end_date'] ?? '';
$employee_id = $_GET['employee_id'] ?? '';

// جلب بيانات الموظفين اللي استلموا رواتبهم مع كل التفاصيل
$reports = [];
try {
    $query = "SELECT 
                e.name AS employee_name,
                sp.payment_date,
                sp.base_salary,
                sp.advance,
                sp.bonuses,
                sp.deductions,
                sp.net_salary,
                t.name AS treasury_name
              FROM salary_payments sp
              JOIN employees e ON sp.employee_id = e.id
              JOIN treasuries t ON sp.treasury_id = t.id";
    
    $conditions = [];
    $params = [];
    if ($start_date && $end_date) {
        $conditions[] = "DATE(sp.payment_date) BETWEEN :start_date AND :end_date";
        $params[':start_date'] = $start_date;
        $params[':end_date'] = $end_date;
    }
    if ($employee_id) {
        $conditions[] = "sp.employee_id = :employee_id";
        $params[':employee_id'] = $employee_id;
    }

    if (!empty($conditions)) {
        $query .= " WHERE " . implode(" AND ", $conditions);
    }

    $stmt = $conn->prepare($query);
    foreach ($params as $key => $value) {
        $stmt->bindParam($key, $value);
    }
    $stmt->execute();
    $reports = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    error_log("Error fetching employee reports: " . $e->getMessage());
    $reports = [];
}
?>

<!DOCTYPE html>
<html lang="ar">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Astra - تقارير الموظفين</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        body {
            margin: 0;
            padding: 0;
            min-height: 100vh;
            direction: rtl;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #2ECC71, #3498DB, #E74C3C);
            overflow-x: hidden;
            animation: gradientShift 10s ease infinite;
            background-size: 400% 400%;
        }

        @keyframes gradientShift {
            0% { background-position: 0% 50%; }
            50% { background-position: 100% 50%; }
            100% { background-position: 0% 50%; }
        }

        .container-fluid {
            padding: 20px;
            height: 100vh;
            display: flex;
            flex-direction: column;
        }

        .card {
            background: rgba(255, 255, 255, 0.95);
            border-radius: 20px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
            padding: 20px;
            margin-bottom: 20px;
            animation: fadeIn 1s ease-in-out;
        }

        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(-20px); }
            to { opacity: 1; transform: translateY(0); }
        }

        h2 {
            color: #2ECC71;
            font-weight: bold;
            text-align: center;
            margin-bottom: 20px;
            text-shadow: 0 0 5px rgba(46, 204, 113, 0.5);
        }

        .form-label {
            color: #3498DB;
            font-weight: bold;
            margin-bottom: 5px;
            display: flex;
            align-items: center;
            font-size: 0.9rem;
        }

        .form-label i {
            margin-left: 8px;
            color: #2ECC71;
        }

        .form-control, .form-select {
            border-radius: 10px;
            border: 2px solid #2ECC71;
            padding: 6px 10px;
            background: rgba(255, 255, 255, 0.8);
            transition: all 0.3s ease;
            box-shadow: inset 0 2px 5px rgba(0, 0, 0, 0.1);
            font-size: 0.9rem;
        }

        .form-control:focus, .form-select:focus {
            border-color: #3498DB;
            box-shadow: 0 0 10px rgba(52, 152, 219, 0.5), inset 0 2px 5px rgba(0, 0, 0, 0.1);
            background: #fff;
        }

        .btn {
            border-radius: 10px;
            padding: 6px 15px;
            font-weight: bold;
            transition: all 0.4s ease;
            position: relative;
            overflow: hidden;
            font-size: 0.9rem;
        }

        .btn-search {
            background: linear-gradient(45deg, #3498DB, #2980B9);
            border: none;
            color: #fff;
        }

        .btn-search:hover {
            background: linear-gradient(45deg, #2980B9, #2471A3);
            transform: translateY(-3px);
            box-shadow: 0 5px 15px rgba(52, 152, 219, 0.5);
        }

        .btn-print {
            background: linear-gradient(45deg, #F1C40F, #D4AC0D);
            border: none;
            color: #fff;
        }

        .btn-print:hover {
            background: linear-gradient(45deg, #D4AC0D, #C39B00);
            transform: translateY(-3px);
            box-shadow: 0 5px 15px rgba(241, 196, 15, 0.5);
        }

        .btn-back {
            background: linear-gradient(45deg, #9B59B6, #8E44AD);
            border: none;
            color: #fff;
        }

        .btn-back:hover {
            background: linear-gradient(45deg, #8E44AD, #7D3C98);
            transform: translateY(-3px);
            box-shadow: 0 5px 15px rgba(155, 89, 182, 0.5);
        }

        .btn i {
            margin-left: 8px;
        }

        .table {
            background: #fff;
            border-radius: 10px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
            width: 100%;
        }

        .table thead {
            background: #2ECC71;
            color: #fff;
        }

        .table tbody tr:hover {
            background: rgba(46, 204, 113, 0.1);
        }

        /* استايل الطباعة */
        @media print {
            body {
                background: #fff;
                direction: rtl;
            }
            .container-fluid, .card {
                box-shadow: none;
                border: none;
                padding: 0;
                margin: 0;
            }
            h2 {
                text-align: center;
                color: #000;
                margin-bottom: 20px;
            }
            .form-row, .btn-back, .btn-print {
                display: none;
            }
            .table {
                width: 100%;
                border-collapse: collapse;
            }
            .table thead {
                background: #2ECC71;
                color: #fff;
            }
            .table th, .table td {
                border: 1px solid #ddd;
                padding: 8px;
                text-align: right;
                font-size: 12px; /* تقليل حجم الخط للطباعة */
            }
            .table-responsive {
                overflow: visible !important; /* إلغاء التمرير أثناء الطباعة */
            }
        }
    </style>
</head>
<body>
    <div class="container-fluid">
        <div class="card">
            <h2><i class="fas fa-file-alt me-2"></i> تقارير الموظفين</h2>

            <!-- فلتر البحث -->
            <form method="GET" class="row g-3 mb-4 form-row">
                <div class="col-md-3">
                    <label class="form-label"><i class="fas fa-user"></i> اختر الموظف</label>
                    <select class="form-select" name="employee_id">
                        <option value="">جميع الموظفين</option>
                        <?php foreach ($employees as $employee): ?>
                            <option value="<?php echo $employee['id']; ?>" <?php echo $employee_id == $employee['id'] ? 'selected' : ''; ?>>
                                <?php echo htmlspecialchars($employee['name']); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-3">
                    <label class="form-label"><i class="fas fa-calendar-alt"></i> من تاريخ</label>
                    <input type="date" class="form-control" name="start_date" value="<?php echo htmlspecialchars($start_date); ?>">
                </div>
                <div class="col-md-3">
                    <label class="form-label"><i class="fas fa-calendar-alt"></i> إلى تاريخ</label>
                    <input type="date" class="form-control" name="end_date" value="<?php echo htmlspecialchars($end_date); ?>">
                </div>
                <div class="col-md-3 d-flex align-items-end">
                    <button type="submit" class="btn btn-search w-100"><i class="fas fa-search"></i> بحث</button>
                </div>
            </form>

            <!-- جدول التقارير -->
            <div class="table-responsive" style="max-height: 50vh; overflow-y: auto;">
                <table class="table table-striped">
                    <thead>
                        <tr>
                            <th>اسم الموظف</th>
                            <th>تاريخ الدفع</th>
                            <th>الراتب الأساسي</th>
                            <th>السلف</th>
                            <th>الحوافز</th>
                            <th>الخصومات</th>
                            <th>المرتب الصافي</th>
                            <th>الخزنة</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (!empty($reports)): ?>
                            <?php foreach ($reports as $report): ?>
                                <tr>
                                    <td><?php echo htmlspecialchars($report['employee_name']); ?></td>
                                    <td><?php echo htmlspecialchars($report['payment_date']); ?></td>
                                    <td><?php echo number_format($report['base_salary'], 2); ?> ج.م</td>
                                    <td><?php echo number_format($report['advance'], 2); ?> ج.م</td>
                                    <td><?php echo number_format($report['bonuses'], 2); ?> ج.م</td>
                                    <td><?php echo number_format($report['deductions'], 2); ?> ج.م</td>
                                    <td><?php echo number_format($report['net_salary'], 2); ?> ج.م</td>
                                    <td><?php echo htmlspecialchars($report['treasury_name']); ?></td>
                                </tr>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <tr><td colspan="8" style="text-align: center; color: #E74C3C;">لا توجد تقارير لموظفين استلموا رواتبهم.</td></tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>

            <div class="text-center mt-3">
                <button class="btn btn-print" onclick="window.print()"><i class="fas fa-print"></i> طباعة</button>
                <button class="btn btn-back" onclick="window.location.href='dashboard.php'"><i class="fas fa-arrow-right"></i> العودة إلى لوحة التحكم</button>
            </div>
        </div>
    </div>

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