<?php
session_start();

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

require_once 'db_connect.php';

// جلب الخزنات
$treasuries = [];
try {
    $treasuries = $conn->query("SELECT * FROM treasuries")->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    error_log("Error fetching treasuries: " . $e->getMessage());
}

$success_message = '';
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if (isset($_POST['add_treasury'])) {
        $name = $_POST['name'] ?? '';
        $previous_balance = $_POST['previous_balance'] ?? 0.00;

        try {
            $stmt = $conn->prepare("INSERT INTO treasuries (name, previous_balance, current_balance) VALUES (:name, :previous_balance, :previous_balance)");
            $stmt->execute([
                ':name' => $name,
                ':previous_balance' => $previous_balance
            ]);

            $success_message = "تم إضافة الخزنة بنجاح!";
            header("Location: treasury_manage.php?success=" . urlencode($success_message));
            exit();
        } catch (PDOException $e) {
            error_log("Error adding treasury: " . $e->getMessage());
            $success_message = "فشل إضافة الخزنة: " . $e->getMessage();
        }
    } elseif (isset($_POST['add_transaction'])) {
        $treasury_id = $_POST['treasury_id'] ?? '';
        $transaction_type = $_POST['transaction_type'] ?? 'deposit';
        $amount = $_POST['amount'] ?? 0.00;
        $description = $_POST['description'] ?? '';

        try {
            // بدء المعاملة لضمان الاتساق
            $conn->beginTransaction();

            // جلب الرصيد الحالي للخزنة
            $stmt = $conn->prepare("SELECT current_balance FROM treasuries WHERE id = :treasury_id");
            $stmt->execute([':treasury_id' => $treasury_id]);
            $current_balance = $stmt->fetchColumn();

            if ($transaction_type === 'deposit') {
                $new_balance = $current_balance + $amount;
            } else { // withdrawal
                if ($current_balance >= $amount) {
                    $new_balance = $current_balance - $amount;
                } else {
                    throw new PDOException("الرصيد غير كافٍ للسحب!");
                }
            }

            // تحديث الرصيد الحالي للخزنة
            $stmt = $conn->prepare("UPDATE treasuries SET current_balance = :new_balance WHERE id = :treasury_id");
            $stmt->execute([':new_balance' => $new_balance, ':treasury_id' => $treasury_id]);

            // تسجيل العملية
            $stmt = $conn->prepare("INSERT INTO treasury_transactions (treasury_id, transaction_type, amount, description) VALUES (:treasury_id, :transaction_type, :amount, :description)");
            $stmt->execute([
                ':treasury_id' => $treasury_id,
                ':transaction_type' => $transaction_type,
                ':amount' => $amount,
                ':description' => $description
            ]);

            // إتمام المعاملة
            $conn->commit();

            $success_message = "تم تنفيذ العملية بنجاح!";
            header("Location: treasury_manage.php?success=" . urlencode($success_message));
            exit();
        } catch (PDOException $e) {
            $conn->rollBack();
            error_log("Error adding transaction: " . $e->getMessage());
            $success_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);
        }
        .btn-info {
            background: linear-gradient(45deg, #3498DB, #2980B9);
            border: none;
            color: #fff;
        }
        .btn-info:hover {
            background: linear-gradient(45deg, #2980B9, #2471A3);
            transform: translateY(-3px);
            box-shadow: 0 5px 15px rgba(52, 152, 219, 0.5);
        }
        .success-message {
            color: #2ECC71;
            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);
        }
        .table thead {
            background: #2ECC71;
            color: #fff;
        }
        .table tbody tr:hover {
            background: rgba(46, 204, 113, 0.1);
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="card">
            <h2><i class="fas fa-lock"></i> إدارة الخزنة</h2>
            <?php if (isset($_GET['success'])): ?>
                <div class="success-message"><?php echo htmlspecialchars($_GET['success']); ?></div>
            <?php endif; ?>

            <!-- نموذج إضافة خزنة جديدة -->
            <h3>إضافة خزنة جديدة</h3>
            <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" 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="0.00" required>
                    </div>
                </div>
                <button type="submit" class="btn btn-primary" name="add_treasury"><i class="fas fa-plus"></i> إضافة خزنة</button>
            </form>

            <!-- نموذج إضافة عملية (إيداع/سحب) -->
            <h3 class="mt-4">إضافة عملية مالية</h3>
            <form method="POST">
                <div class="row g-3 mb-3">
                    <div class="col-md-4">
                        <label class="form-label"><i class="fas fa-vault"></i> اختر الخزنة</label>
                        <select class="form-select" name="treasury_id" required>
                            <?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; ?>
                        </select>
                    </div>
                    <div class="col-md-4">
                        <label class="form-label"><i class="fas fa-exchange-alt"></i> نوع العملية</label>
                        <select class="form-select" name="transaction_type" required>
                            <option value="deposit">إيداع</option>
                            <option value="withdrawal">سحب</option>
                        </select>
                    </div>
                    <div class="col-md-4">
                        <label class="form-label"><i class="fas fa-money-bill"></i> المبلغ</label>
                        <input type="number" step="0.01" class="form-control" name="amount" required>
                    </div>
                    <div class="col-md-12">
                        <label class="form-label"><i class="fas fa-comment"></i> الوصف (اختياري)</label>
                        <textarea class="form-control" name="description"></textarea>
                    </div>
                </div>
                <button type="submit" class="btn btn-primary" name="add_transaction"><i class="fas fa-plus"></i> تنفيذ العملية</button>
            </form>

            <!-- عرض قائمة الخزنات -->
            <h3 class="mt-4">قائمة الخزنات</h3>
            <table class="table table-striped mt-3">
                <thead>
                    <tr>
                        <th>الرقم</th>
                        <th>اسم الخزنة</th>
                        <th>الرصيد السابق</th>
                        <th>الرصيد الحالي</th>
                        <th>تاريخ الإنشاء</th>
                        <th>الإجراءات</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($treasuries as $treasury): ?>
                        <tr>
                            <td><?php echo $treasury['id']; ?></td>
                            <td><?php echo htmlspecialchars($treasury['name']); ?></td>
                            <td><?php echo number_format($treasury['previous_balance'], 2); ?> ج.م</td>
                            <td><?php echo number_format($treasury['current_balance'], 2); ?> ج.م</td>
                            <td><?php echo $treasury['created_at']; ?></td>
                            <td>
                                <a href="edit_treasury.php?id=<?php echo $treasury['id']; ?>" class="btn btn-primary btn-sm"><i class="fas fa-edit"></i> تعديل</a>
                                <a href="delete_treasury.php?id=<?php echo $treasury['id']; ?>" class="btn btn-danger btn-sm" onclick="return confirm('هل أنت متأكد من حذف هذه الخزنة؟')"><i class="fas fa-trash"></i> حذف</a>
                                <a href="treasury.php?treasury_id=<?php echo $treasury['id']; ?>" class="btn btn-info btn-sm"><i class="fas fa-eye"></i> عرض التفاصيل</a>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>

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