<?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 * FROM employees ORDER BY id DESC")->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    error_log("Error fetching employees: " . $e->getMessage());
    $employees = [];
}

// معالجة إضافة موظف
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['add_employee'])) {
    $name = trim($_POST['name']);
    $address = trim($_POST['address']);
    $mobile = trim($_POST['mobile']);
    $salary = floatval(str_replace(',', '', trim($_POST['salary'])));

    if (!empty($name) && !empty($address) && !empty($mobile) && $salary > 0) {
        try {
            $stmt = $conn->prepare("INSERT INTO employees (name, address, mobile, salary) VALUES (:name, :address, :mobile, :salary)");
            $stmt->execute([
                ':name' => $name,
                ':address' => $address,
                ':mobile' => $mobile,
                ':salary' => $salary
            ]);
            header("Location: employee_management.php");
            exit();
        } catch (PDOException $e) {
            error_log("Error adding employee: " . $e->getMessage());
        }
    }
}

// معالجة تعديل موظف
$success_message = '';
$error_message = '';
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['edit_employee'])) {
    $id = intval($_POST['id']);
    $name = trim($_POST['name']);
    $address = trim($_POST['address']);
    $mobile = trim($_POST['mobile']);
    $salary = floatval(str_replace(',', '', trim($_POST['salary'])));

    if ($id > 0 && !empty($name) && !empty($address) && !empty($mobile) && $salary > 0) {
        try {
            $stmt = $conn->prepare("UPDATE employees SET name = :name, address = :address, mobile = :mobile, salary = :salary WHERE id = :id");
            $stmt->execute([
                ':id' => $id,
                ':name' => $name,
                ':address' => $address,
                ':mobile' => $mobile,
                ':salary' => $salary
            ]);
            $success_message = "تم تعديل بيانات الموظف بنجاح!";
            // header("Location: employee_management.php");
            // exit();
        } catch (PDOException $e) {
            error_log("Error updating employee: " . $e->getMessage());
            $error_message = "فشل تعديل بيانات الموظف: " . $e->getMessage();
        }
    } else {
        $error_message = "يرجى ملء جميع الحقول بشكل صحيح.";
    }
}

// معالجة حذف موظف
if (isset($_GET['delete_id']) && intval($_GET['delete_id']) > 0) {
    $id = intval($_GET['delete_id']);
    try {
        $stmt = $conn->prepare("DELETE FROM employees WHERE id = :id");
        $stmt->execute([':id' => $id]);
        header("Location: employee_management.php");
        exit();
    } catch (PDOException $e) {
        error_log("Error deleting employee: " . $e->getMessage());
    }
}
?>

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

        .btn-add:hover {
            background: linear-gradient(45deg, #27AE60, #219653);
            transform: translateY(-3px);
            box-shadow: 0 5px 15px rgba(46, 204, 113, 0.5);
        }

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

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

        .btn-delete {
            background: linear-gradient(45deg, #E74C3C, #C0392B);
            border: none;
            color: #fff;
        }

        .btn-delete:hover {
            background: linear-gradient(45deg, #C0392B, #A93226);
            transform: translateY(-3px);
            box-shadow: 0 5px 15px rgba(231, 76, 60, 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);
        }

        .edit-form {
            display: none;
            margin-top: 20px;
        }

        .error-message {
            color: #E74C3C;
            text-align: center;
            margin-top: 10px;
        }
    </style>
</head>
<body>
    <div class="container-fluid">
        <div class="card">
            <h2><i class="fas fa-users-cog 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="addEmployeeForm">
                <div class="row g-3">
                    <div class="col-md-3">
                        <label class="form-label"><i class="fas fa-user"></i> اسم الموظف</label>
                        <input type="text" class="form-control" name="name" required>
                    </div>
                    <div class="col-md-3">
                        <label class="form-label"><i class="fas fa-map-marker-alt"></i> العنوان</label>
                        <input type="text" class="form-control" name="address" required>
                    </div>
                    <div class="col-md-2">
                        <label class="form-label"><i class="fas fa-phone"></i> الموبايل</label>
                        <input type="text" class="form-control" name="mobile" required pattern="[0-9]{11}" placeholder="مثال: 01234567890">
                    </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="salary" required>
                    </div>
                    <div class="col-md-2">
                        <label class="form-label"> </label>
                        <button type="submit" class="btn btn-add w-100" name="add_employee"><i class="fas fa-plus"></i> إضافة موظف</button>
                    </div>
                </div>
            </form>

            <?php if (!empty($employees)): ?>
                <div class="table-responsive" style="max-height: 50vh; overflow-y: auto; margin-top: 20px;">
                    <table class="table table-striped">
                        <thead>
                            <tr>
                                <th>الرقم</th>
                                <th>الاسم</th>
                                <th>العنوان</th>
                                <th>الموبايل</th>
                                <th>الراتب</th>
                                <th>التحكم</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($employees as $employee): ?>
                                <tr>
                                    <td><?php echo htmlspecialchars($employee['id']); ?></td>
                                    <td><?php echo htmlspecialchars($employee['name']); ?></td>
                                    <td><?php echo htmlspecialchars($employee['address']); ?></td>
                                    <td><?php echo htmlspecialchars($employee['mobile']); ?></td>
                                    <td><?php echo number_format($employee['salary'], 2); ?> ج.م</td>
                                    <td>
                                        <button class="btn btn-edit" onclick="showEditForm('<?php echo $employee['id']; ?>', '<?php echo htmlspecialchars($employee['name']); ?>', '<?php echo htmlspecialchars($employee['address']); ?>', '<?php echo htmlspecialchars($employee['mobile']); ?>', '<?php echo $employee['salary']; ?>')"><i class="fas fa-edit"></i> تعديل</button>
                                        <a href="?delete_id=<?php echo $employee['id']; ?>" class="btn btn-delete" onclick="return confirm('هل أنت متأكد من حذف الموظف؟')"><i class="fas fa-trash"></i> حذف</a>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php else: ?>
                <p style="color: #E74C3C; text-align: center; margin-top: 20px;">لا يوجد موظفين مسجلين حاليًا.</p>
            <?php endif; ?>

            <!-- نموذج تعديل موظف -->
            <div id="editForm" class="edit-form card p-3 mt-3">
                <h4><i class="fas fa-edit me-2"></i> تعديل بيانات الموظف</h4>
                <form method="POST" id="editEmployeeForm">
                    <input type="hidden" name="id" id="edit_id">
                    <div class="row g-3">
                        <div class="col-md-3">
                            <label class="form-label"><i class="fas fa-user"></i> اسم الموظف</label>
                            <input type="text" class="form-control" name="name" id="edit_name" required>
                        </div>
                        <div class="col-md-3">
                            <label class="form-label"><i class="fas fa-map-marker-alt"></i> العنوان</label>
                            <input type="text" class="form-control" name="address" id="edit_address" required>
                        </div>
                        <div class="col-md-2">
                            <label class="form-label"><i class="fas fa-phone"></i> الموبايل</label>
                            <input type="text" class="form-control" name="mobile" id="edit_mobile" required pattern="[0-9]{11}" placeholder="مثال: 01234567890">
                        </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="salary" id="edit_salary" required>
                        </div>
                        <div class="col-md-2">
                            <label class="form-label"> </label>
                            <button type="submit" class="btn btn-edit w-100" name="edit_employee"><i class="fas fa-save"></i> حفظ التعديل</button>
                        </div>
                    </div>
                </form>
                <button class="btn btn-back mt-2" onclick="hideEditForm()"><i class="fas fa-times"></i> إلغاء</button>
            </div>

            <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 showEditForm(id, name, address, mobile, salary) {
            document.getElementById('edit_id').value = id;
            document.getElementById('edit_name').value = name;
            document.getElementById('edit_address').value = address;
            document.getElementById('edit_mobile').value = mobile;
            document.getElementById('edit_salary').value = salary;
            document.getElementById('editForm').style.display = 'block';

            // التمرير للنموذج
            document.getElementById('editForm').scrollIntoView({ behavior: 'smooth' });
        }

        function hideEditForm() {
            document.getElementById('editForm').style.display = 'none';
        }
    </script>
</body>
</html>