<?php
session_start();

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

require_once 'db_connect.php';

// جلب بيانات المستخدم الحالي
$user_id = $_SESSION['user_id'];
$user_name = $_SESSION['user_name'] ?? '';
if (empty($user_name)) {
    try {
        $stmt = $conn->prepare("SELECT username FROM users WHERE id = :user_id");
        $stmt->execute([':user_id' => $user_id]);
        $user = $stmt->fetch(PDO::FETCH_ASSOC) ?: [];
        if (!empty($user) && isset($user['username'])) {
            $user_name = $user['username'];
            $_SESSION['user_name'] = $user_name;
        }
    } catch (PDOException $e) {
        error_log("Error fetching user name: " . $e->getMessage());
        $user_name = 'مستخدم غير محدد';
    }
}

// معالجة الإضافة
$success_message = '';
$error_message = '';

if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['add_expense_type'])) {
    $name = trim($_POST['name'] ?? '');

    if (empty($name)) {
        $error_message = "اسم نوع المصروف مطلوب!";
    } else {
        try {
            $stmt = $conn->prepare("INSERT INTO expense_types (name) VALUES (:name)");
            $stmt->execute([':name' => $name]);
            $success_message = "تم إضافة نوع المصروف بنجاح!";
        } catch (PDOException $e) {
            error_log("Error adding expense type: " . $e->getMessage());
            $error_message = "فشل إضافة نوع المصروف: " . $e->getMessage();
        }
    }
}

// معالجة التعديل
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['edit_expense_type'])) {
    $id = $_POST['id'] ?? 0;
    $name = trim($_POST['name'] ?? '');

    if (empty($id) || empty($name)) {
        $error_message = "بيانات غير كاملة!";
    } else {
        try {
            $stmt = $conn->prepare("UPDATE expense_types SET name = :name WHERE id = :id");
            $stmt->execute([':name' => $name, ':id' => $id]);
            $success_message = "تم تعديل نوع المصروف بنجاح!";
        } catch (PDOException $e) {
            error_log("Error editing expense type: " . $e->getMessage());
            $error_message = "فشل تعديل نوع المصروف: " . $e->getMessage();
        }
    }
}

// معالجة الحذف
if (isset($_GET['delete']) && $_GET['delete'] > 0) {
    $id = $_GET['delete'];
    try {
        $stmt = $conn->prepare("DELETE FROM expense_types WHERE id = :id");
        $stmt->execute([':id' => $id]);
        $success_message = "تم حذف نوع المصروف بنجاح!";
    } catch (PDOException $e) {
        error_log("Error deleting expense type: " . $e->getMessage());
        $error_message = "فشل حذف نوع المصروف: " . $e->getMessage();
    }
}

// جلب جميع أنواع المصروفات
$expense_types = [];
try {
    $expense_types = $conn->query("SELECT * FROM expense_types ORDER BY created_at DESC")->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    error_log("Error fetching expense types: " . $e->getMessage());
    $expense_types = [];
}
?>

<!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-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;
        }

        .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-cancel {
            background: linear-gradient(45deg, #9B59B6, #8E44AD);
            border: none;
            color: #fff;
        }

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

        .success-message {
            color: #2ECC71;
            font-weight: bold;
            text-align: center;
            margin-bottom: 20px;
            animation: fadeIn 0.5s ease-in-out;
        }

        .error-message {
            color: #E74C3C;
            font-weight: bold;
            text-align: center;
            margin-bottom: 20px;
            animation: fadeIn 0.5s ease-in-out;
        }

        .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);
        }
    </style>
</head>
<body>
    <div class="container-fluid">
        <div class="card">
            <h2><i class="fas fa-money-bill-wave me-2"></i> أنواع المصروفات</h2>
            <?php if ($success_message): ?>
                <div class="success-message"><?php echo $success_message; ?></div>
            <?php endif; ?>
            <?php if ($error_message): ?>
                <div class="error-message"><?php echo $error_message; ?></div>
            <?php endif; ?>

            <!-- نموذج الإضافة -->
            <form method="POST" class="mb-4">
                <div class="row g-3">
                    <div class="col-md-4">
                        <label class="form-label"><i class="fas fa-tag"></i> اسم نوع المصروف</label>
                        <input type="text" class="form-control" name="name" placeholder="أدخل اسم نوع المصروف" required>
                    </div>
                    <div class="col-md-2">
                        <button type="submit" class="btn btn-add" name="add_expense_type"><i class="fas fa-plus"></i> إضافة</button>
                    </div>
                    <div class="col-md-2">
                        <button type="button" class="btn btn-cancel" onclick="window.location.href='dashboard.php'"><i class="fas fa-times"></i> إلغاء</button>
                    </div>
                </div>
            </form>

            <!-- جدول العرض والتعديل والحذف -->
            <div class="table-responsive" style="max-height: 60vh; overflow-y: auto;">
                <table class="table table-striped">
                    <thead>
                        <tr>
                            <th>رقم</th>
                            <th>اسم نوع المصروف</th>
                            <th>تاريخ الإنشاء</th>
                            <th>تاريخ آخر تعديل</th>
                            <th>الإجراءات</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (!empty($expense_types)): ?>
                            <?php foreach ($expense_types as $index => $expense): ?>
                                <tr>
                                    <td><?php echo $index + 1; ?></td>
                                    <td>
                                        <?php if (isset($_GET['edit']) && $_GET['edit'] == $expense['id']): ?>
                                            <form method="POST" style="display:inline;">
                                                <input type="hidden" name="id" value="<?php echo $expense['id']; ?>">
                                                <input type="text" class="form-control d-inline-block w-75" name="name" value="<?php echo htmlspecialchars($expense['name']); ?>" required>
                                                <button type="submit" class="btn btn-edit btn-sm" name="edit_expense_type"><i class="fas fa-save"></i></button>
                                            </form>
                                        <?php else: ?>
                                            <?php echo htmlspecialchars($expense['name']); ?>
                                        <?php endif; ?>
                                    </td>
                                    <td><?php echo date('Y-m-d H:i', strtotime($expense['created_at'])); ?></td>
                                    <td><?php echo $expense['updated_at'] ? date('Y-m-d H:i', strtotime($expense['updated_at'])) : 'غير محدث'; ?></td>
                                    <td>
                                        <?php if (!isset($_GET['edit']) || $_GET['edit'] != $expense['id']): ?>
                                            <a href="?edit=<?php echo $expense['id']; ?>" class="btn btn-edit btn-sm"><i class="fas fa-edit"></i> تعديل</a>
                                            <a href="?delete=<?php echo $expense['id']; ?>" class="btn btn-delete btn-sm" onclick="return confirm('هل أنت متأكد من حذف هذا النوع؟');"><i class="fas fa-trash"></i> حذف</a>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <tr><td colspan="5" style="text-align: center; color: #E74C3C;">لا توجد أنواع مصروفات.</td></tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

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