<?php
session_start();

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

require_once 'db_connect.php';

$treasury = null;
$success_message = '';
$error_message = '';

// جلب بيانات الخزنة بناءً على معرفها
if (isset($_GET['id']) && is_numeric($_GET['id'])) {
    try {
        $stmt = $conn->prepare("SELECT * FROM treasuries WHERE id = :id");
        $stmt->execute([':id' => $_GET['id']]);
        $treasury = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$treasury) {
            $error_message = "لم يتم العثور على الخزنة!";
            header("Location: treasury_manage.php?error=" . urlencode($error_message));
            exit();
        }
    } catch (PDOException $e) {
        error_log("Error fetching treasury: " . $e->getMessage());
        $error_message = "حدث خطأ أثناء جلب بيانات الخزنة: " . $e->getMessage();
    }
} else {
    header("Location: treasury_manage.php?error=معرف الخزنة غير صالح");
    exit();
}

// معالجة التعديل
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $name = $_POST['name'] ?? '';
    $previous_balance = $_POST['previous_balance'] ?? 0.00;

    try {
        // تحديث بيانات الخزنة
        $stmt = $conn->prepare("UPDATE treasuries SET name = :name, previous_balance = :previous_balance, updated_at = NOW() WHERE id = :id");
        $stmt->execute([
            ':name' => $name,
            ':previous_balance' => $previous_balance,
            ':id' => $_GET['id']
        ]);

        // تحديث الرصيد الحالي بناءً على الرصيد السابق الجديد إذا لزم الأمر
        $stmt = $conn->prepare("SELECT SUM(CASE WHEN transaction_type = 'deposit' THEN amount WHEN transaction_type = 'withdrawal' THEN -amount ELSE 0 END) as balance_change FROM treasury_transactions WHERE treasury_id = :treasury_id");
        $stmt->execute([':treasury_id' => $_GET['id']]);
        $balance_change = $stmt->fetchColumn() ?: 0;

        $new_current_balance = $previous_balance + $balance_change;
        $stmt = $conn->prepare("UPDATE treasuries SET current_balance = :current_balance WHERE id = :id");
        $stmt->execute([
            ':current_balance' => $new_current_balance,
            ':id' => $_GET['id']
        ]);

        $success_message = "تم تعديل الخزنة بنجاح!";
        header("Location: treasury_manage.php?success=" . urlencode($success_message));
        exit();
    } catch (PDOException $e) {
        error_log("Error updating treasury: " . $e->getMessage());
        $error_message = "فشل تعديل الخزنة: " . $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 {
            direction: rtl;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #2ECC71, #3498DB, #E74C3C);
            min-height: 100vh;
        }
        .container {
            padding: 20px;
        }
        .card {
            background: rgba(255, 255, 255, 0.95);
            border-radius: 20px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
            padding: 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;
        }
        .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);
        }
        .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;
        }
        .btn-primary {
            background: linear-gradient(45deg, #2ECC71, #27AE60);
            border: none;
            color: #fff;
        }
        .btn-primary:hover {
            background: linear-gradient(45deg, #27AE60, #219653);
            transform: translateY(-3px);
            box-shadow: 0 5px 15px rgba(46, 204, 113, 0.5);
        }
        .btn-danger {
            background: linear-gradient(45deg, #E74C3C, #C0392B);
            border: none;
            color: #fff;
        }
        .btn-danger:hover {
            background: linear-gradient(45deg, #C0392B, #A93226);
            transform: translateY(-3px);
            box-shadow: 0 5px 15px rgba(231, 76, 60, 0.5);
        }
        .success-message, .error-message {
            text-align: center;
            margin-bottom: 20px;
            animation: fadeIn 0.5s ease-in-out;
        }
        .success-message {
            color: #2ECC71;
            font-weight: bold;
        }
        .error-message {
            color: #E74C3C;
            font-weight: bold;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="card">
            <h2><i class="fas fa-edit"></i> تعديل الخزنة</h2>
            <?php if (isset($success_message)): ?>
                <div class="success-message"><?php echo htmlspecialchars($success_message); ?></div>
            <?php endif; ?>
            <?php if (isset($error_message)): ?>
                <div class="error-message"><?php echo htmlspecialchars($error_message); ?></div>
            <?php endif; ?>

            <?php if ($treasury): ?>
                <form method="POST">
                    <div class="row g-3 mb-3">
                        <div class="col-md-6">
                            <label class="form-label"><i class="fas fa-vault"></i> اسم الخزنة</label>
                            <input type="text" class="form-control" name="name" value="<?php echo htmlspecialchars($treasury['name']); ?>" required>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label"><i class="fas fa-money-bill"></i> الرصيد السابق</label>
                            <input type="number" step="0.01" class="form-control" name="previous_balance" value="<?php echo number_format($treasury['previous_balance'], 2); ?>" required>
                        </div>
                    </div>
                    <button type="submit" class="btn btn-primary"><i class="fas fa-save"></i> حفظ التعديلات</button>
                    <a href="treasury_manage.php" class="btn btn-danger"><i class="fas fa-times"></i> إلغاء</a>
                </form>
            <?php else: ?>
                <p class="error-message">لم يتم العثور على الخزنة!</p>
            <?php endif; ?>
        </div>
    </div>

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