<?php
session_start();

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

require_once 'db_connect.php';

// جلب اسم المستخدم الحالي
$user_name = $_SESSION['user_name'] ?? 'مستخدم غير محدد';

// جلب قائمة الموظفين
$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 = [];
}

// جلب قائمة الخزنات
$treasuries = [];
$treasury_error = '';
try {
    $stmt = $conn->prepare("SELECT id, name, current_balance FROM treasuries");
    $stmt->execute();
    $treasuries = $stmt->fetchAll(PDO::FETCH_ASSOC);
    if (empty($treasuries)) {
        $treasury_error = "لا توجد خزنات مسجلة في النظام. يرجى إضافتها أولاً.";
    }
} catch (PDOException $e) {
    error_log("Error fetching treasuries: " . $e->getMessage());
    $treasury_error = "حدث خطأ أثناء جلب الخزنات: " . $e->getMessage();
}

// معالجة حفظ دفع الراتب
$success_message = '';
$error_message = '';
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['save_payment'])) {
    $employee_id = intval($_POST['employee_id']);
    $payment_date = trim($_POST['payment_date']);
    $month_year = trim($_POST['month_year']);
    $advance = floatval(str_replace(',', '', trim($_POST['advance'] ?? 0)));
    $bonuses = floatval(str_replace(',', '', trim($_POST['bonuses'] ?? 0)));
    $deductions = floatval(str_replace(',', '', trim($_POST['deductions'] ?? 0)));
    $treasury_id = intval($_POST['treasury_id']);

    // جلب الراتب الأساسي للموظف واسم الموظف
    $base_salary = 0;
    $employee_name = '';
    try {
        $stmt = $conn->prepare("SELECT salary, name FROM employees WHERE id = :id");
        $stmt->execute([':id' => $employee_id]);
        $employee = $stmt->fetch(PDO::FETCH_ASSOC);
        $base_salary = $employee ? floatval($employee['salary']) : 0;
        $employee_name = $employee ? $employee['name'] : 'غير معروف';
    } catch (PDOException $e) {
        error_log("Error fetching employee salary: " . $e->getMessage());
    }

    // حساب المرتب الصافي
    $net_salary = $base_salary + $bonuses - $advance - $deductions;

    if ($employee_id > 0 && !empty($payment_date) && !empty($month_year) && $net_salary > 0 && $treasury_id > 0) {
        try {
            // بدء المعاملة لضمان التناسق
            $conn->beginTransaction();

            // تسجيل دفع الراتب
            $stmt = $conn->prepare("INSERT INTO salary_payments (employee_id, payment_date, month_year, base_salary, advance, bonuses, deductions, net_salary, treasury_id) VALUES (:employee_id, :payment_date, :month_year, :base_salary, :advance, :bonuses, :deductions, :net_salary, :treasury_id)");
            $stmt->execute([
                ':employee_id' => $employee_id,
                ':payment_date' => $payment_date,
                ':month_year' => $month_year,
                ':base_salary' => $base_salary,
                ':advance' => $advance,
                ':bonuses' => $bonuses,
                ':deductions' => $deductions,
                ':net_salary' => $net_salary,
                ':treasury_id' => $treasury_id
            ]);

            // خصم المبلغ من الخزنة
            $stmt = $conn->prepare("UPDATE treasuries SET current_balance = current_balance - :net_salary WHERE id = :treasury_id AND current_balance >= :net_salary");
            $stmt->execute([':net_salary' => $net_salary, ':treasury_id' => $treasury_id]);
            if ($stmt->rowCount() == 0) {
                throw new Exception("رصيد الخزنة غير كافٍ أو حدث خطأ في الخصم!");
            }

            // تسجيل العملية في treasury_transactions
            $description = "دفع مرتب للموظف: $employee_name (شهر $month_year)";
            $stmt = $conn->prepare("INSERT INTO treasury_transactions (treasury_id, amount, transaction_type, description, date) VALUES (:treasury_id, :amount, 'withdrawal', :description, :date)");
            $stmt->execute([
                ':treasury_id' => $treasury_id,
                ':amount' => $net_salary,
                ':description' => $description,
                ':date' => $payment_date
            ]);

            $conn->commit();
            $success_message = "تم دفع الراتب بنجاح وخصم المبلغ من الخزنة!";
            header("Location: salary_payments.php");
            exit();
        } catch (PDOException $e) {
            $conn->rollBack();
            error_log("Error saving salary payment: " . $e->getMessage());
            $error_message = "فشل دفع الراتب: " . $e->getMessage();
        } catch (Exception $e) {
            $conn->rollBack();
            error_log("Error: " . $e->getMessage());
            $error_message = $e->getMessage();
        }
    } else {
        $error_message = "يرجى ملء جميع الحقول بشكل صحيح.";
    }
}



?>

<!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-save {
            background: linear-gradient(45deg, #2ECC71, #27AE60);
            border: none;
            color: #fff;
        }

        .btn-save:hover {
            background: linear-gradient(45deg, #27AE60, #219653);
            transform: translateY(-3px);
            box-shadow: 0 5px 15px rgba(46, 204, 113, 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;
        }

        .net-salary {
            background: #fff;
            padding: 10px;
            border-radius: 10px;
            border: 2px solid #2ECC71;
            font-weight: bold;
            color: #E74C3C;
            text-align: center;
            margin-top: 20px;
        }
    </style>
</head>
<body>
    <div class="container-fluid">
        <div class="card">
            <h2><i class="fas fa-money-check-alt me-2"></i> دفع الرواتب</h2>
            <?php if (!empty($success_message)): ?>
                <div class="success-message" style="color: #2ECC71; text-align: center; margin-bottom: 20px;">
                    <?php echo $success_message; ?>
                </div>
            <?php endif; ?>
            <?php if (!empty($error_message)): ?>
                <div class="error-message" style="color: #E74C3C; text-align: center; margin-bottom: 20px;">
                    <?php echo $error_message; ?>
                </div>
            <?php endif; ?>

            <form method="POST" id="salaryPaymentForm">
                <div class="row g-3">
                    <div class="col-md-3">
                        <label class="form-label"><i class="fas fa-user"></i> اسم الموظف</label>
                        <select class="form-select" name="employee_id" id="employee_id" onchange="updateSalary()" required>
                            <option value="">اختر موظفًا</option>
                            <?php foreach ($employees as $employee): ?>
                                <option value="<?php echo $employee['id']; ?>">
                                    <?php echo htmlspecialchars($employee['name']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <label class="form-label"><i class="fas fa-calendar-day"></i> تاريخ اليوم</label>
                        <input type="date" class="form-control" name="payment_date" id="payment_date" value="<?php echo date('Y-m-d'); ?>" required readonly>
                    </div>
                    <div class="col-md-2">
                        <label class="form-label"><i class="fas fa-calendar-alt"></i> تاريخ الشهر</label>
                        <input type="month" class="form-control" name="month_year" id="month_year" value="<?php echo date('Y-m'); ?>" required>
                    </div>
                    <div class="col-md-2">
                        <label class="form-label"><i class="fas fa-money-bill"></i> الراتب الأساسي</label>
                        <input type="number" step="0.01" class="form-control" name="base_salary" id="base_salary" readonly>
                    </div>
                    <div class="col-md-3">
                        <label class="form-label"> </label>
                        <button type="submit" class="btn btn-save w-100" name="save_payment"><i class="fas fa-save"></i> حفظ الدفع</button>
                    </div>
                </div>
                <div class="row g-3 mt-3">
                    <div class="col-md-2">
                        <label class="form-label"><i class="fas fa-hand-holding-usd"></i> السلف</label>
                        <input type="number" step="0.01" class="form-control" name="advance" id="advance" value="0" oninput="calculateNetSalary()">
                    </div>
                    <div class="col-md-2">
                        <label class="form-label"><i class="fas fa-gift"></i> الحوافز</label>
                        <input type="number" step="0.01" class="form-control" name="bonuses" id="bonuses" value="0" oninput="calculateNetSalary()">
                    </div>
                    <div class="col-md-2">
                        <label class="form-label"><i class="fas fa-minus-circle"></i> الخصومات</label>
                        <input type="number" step="0.01" class="form-control" name="deductions" id="deductions" value="0" oninput="calculateNetSalary()">
                    </div>
                    <div class="col-md-3">
                        <label class="form-label"><i class="fas fa-calculator"></i> صافي المرتب</label>
                        <input type="number" step="0.01" class="form-control net-salary" name="net_salary" id="net_salary" readonly>
                    </div>
                    <div class="col-md-3">
                        <label class="form-label"><i class="fas fa-lock"></i> الخزنة</label>
                        <select class="form-select" name="treasury_id" id="treasury_id" required>
                            <option value="">اختر خزنة</option>
                            <?php if (!empty($treasuries)): ?>
                                <?php foreach ($treasuries as $treasury): ?>
                                    <option value="<?php echo $treasury['id']; ?>">
                                        <?php echo htmlspecialchars($treasury['name']) . " (رصيد: " . number_format($treasury['current_balance'], 2) . " ج.م)"; ?>
                                    </option>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <option value="" disabled><?php echo $treasury_error ?: 'لا توجد خزنات متاحة'; ?></option>
                            <?php endif; ?>
                        </select>
                    </div>
                </div>
            </form>

            <div class="text-center mt-3">
                <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>
    <script>
        function updateSalary() {
            const employeeId = document.getElementById('employee_id').value;
            if (employeeId) {
                fetch('get_salary.php?employee_id=' + employeeId)
                    .then(response => response.json())
                    .then(data => {
                        if (data.status === 'success') {
                            document.getElementById('base_salary').value = data.salary;
                            calculateNetSalary();
                        } else {
                            document.getElementById('base_salary').value = 0;
                            calculateNetSalary();
                        }
                    })
                    .catch(error => console.error('Error:', error));
            } else {
                document.getElementById('base_salary').value = 0;
                calculateNetSalary();
            }
        }

        function calculateNetSalary() {
            const baseSalary = parseFloat(document.getElementById('base_salary').value) || 0;
            const advance = parseFloat(document.getElementById('advance').value) || 0;
            const bonuses = parseFloat(document.getElementById('bonuses').value) || 0;
            const deductions = parseFloat(document.getElementById('deductions').value) || 0;
            const netSalary = baseSalary + bonuses - advance - deductions;
            document.getElementById('net_salary').value = netSalary.toFixed(2);
        }

        // تحديث الراتب عند تحميل الصفحة
        window.onload = function() {
            updateSalary();
        };
    </script>
</body>
</html>