<?php
session_start();

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

require_once 'db_connect.php';

// جلب الخزنات
$treasuries = [];
try {
    $treasuries = $conn->query("SELECT id, name, current_balance FROM treasuries")->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    error_log("Error fetching treasuries: " . $e->getMessage());
    $treasuries[] = ['id' => 1, 'name' => 'الخزنة الافتراضية', 'current_balance' => 0];
}

// معالجة البحث
$selected_treasury_id = $_GET['treasury_id'] ?? ($treasuries[0]['id'] ?? 1);
$start_date = $_GET['start_date'] ?? '';
$end_date = $_GET['end_date'] ?? '';
$search_query = $_GET['search'] ?? '';

// جلب المعاملات من جدول treasury_transactions للخزنة المختارة
$transactions = [];
try {
    $query = "SELECT tt.* 
              FROM treasury_transactions tt 
              WHERE tt.treasury_id = :treasury_id";
    
    if ($start_date && $end_date) {
        $query .= " AND DATE(tt.date) BETWEEN :start_date AND :end_date";
    }
    
    if ($search_query) {
        $query .= " AND tt.description LIKE :search";
    }

    $stmt = $conn->prepare($query);
    $stmt->bindParam(':treasury_id', $selected_treasury_id, PDO::PARAM_INT);
    if ($start_date && $end_date) {
        $stmt->bindParam(':start_date', $start_date);
        $stmt->bindParam(':end_date', $end_date);
    }
if ($search_query) {
            $search_param = "%$search_query%";
        $stmt->bindParam(':search', $search_param);
    }
    $stmt->execute();
    $transactions = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    error_log("Error fetching treasury transactions: " . $e->getMessage());
}

// جلب الرصيد الحالي للخزنة المختارة
$current_balance = 0;
foreach ($treasuries as $treasury) {
    if ($treasury['id'] == $selected_treasury_id) {
        $current_balance = $treasury['current_balance'];
        break;
    }
}
?>

<!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, #3491DB, #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-search {
            background: linear-gradient(45deg, #3498DB, #2980B9);
            border: none;
            color: #fff;
        }

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

        .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);
        }

        .balance-box {
            background: linear-gradient(45deg, #F1C40F, #D4AC0D);
            color: #fff;
            padding: 15px 25px;
            border-radius: 15px;
            box-shadow: 0 5px 15px rgba(241, 196, 15, 0.5);
            text-align: center;
            font-weight: bold;
            font-size: 1.5rem;
            margin-bottom: 20px;
        }

        .transaction-type-deposit { color: #28A745; font-weight: bold; }
        .transaction-type-withdrawal { color: #DC3545; font-weight: bold; }
        .transaction-type-income { color: #17A2B8; font-weight: bold; }
        .transaction-type-pending { color: #FFC107; font-weight: bold; }
    </style>
</head>
<body>
    <div class="container-fluid">
        <div class="card">
            <h2><i class="fas fa-vault me-2"></i> إدارة الخزنة</h2>

            <!-- فلتر البحث -->
            <form method="GET" class="row g-3 mb-4">
                <div class="col-md-3">
                    <label class="form-label"><i class="fas fa-vault"></i> اختر الخزنة</label>
                    <select class="form-select" name="treasury_id" onchange="this.form.submit()">
                        <?php foreach ($treasuries as $treasury): ?>
                            <?php if (!$search_query || stripos($treasury['name'], $search_query) !== false): ?>
                                <option value="<?php echo $treasury['id']; ?>" <?php echo $selected_treasury_id == $treasury['id'] ? 'selected' : ''; ?>>
                                    <?php echo htmlspecialchars($treasury['name']); ?>
                                </option>
                            <?php endif; ?>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-3">
                    <label class="form-label"><i class="fas fa-search"></i> بحث بالوصف أو رقم الفاتورة</label>
                    <input type="text" class="form-control" name="search" value="<?php echo htmlspecialchars($search_query); ?>" placeholder="ابحث بالوصف أو رقم الفاتورة">
                </div>
                <div class="col-md-2">
                    <label class="form-label"><i class="fas fa-calendar-alt"></i> من تاريخ</label>
                    <input type="date" class="form-control" name="start_date" value="<?php echo htmlspecialchars($start_date); ?>">
                </div>
                <div class="col-md-2">
                    <label class="form-label"><i class="fas fa-calendar-alt"></i> إلى تاريخ</label>
                    <input type="date" class="form-control" name="end_date" value="<?php echo htmlspecialchars($end_date); ?>">
                </div>
                <div class="col-md-2 d-flex align-items-end">
                    <button type="submit" class="btn btn-search"><i class="fas fa-search"></i> بحث</button>
                </div>
            </form>

            <!-- عرض الرصيد -->
            <div class="balance-box">
                الرصيد الحالي: <span><?php echo number_format($current_balance, 2); ?></span> ج.م
            </div>

            <!-- جدول المعاملات -->
            <div class="table-responsive" style="max-height: 50vh; overflow-y: auto;">
                <table class="table table-striped">
                    <thead>
                        <tr>
                            <th>التاريخ</th>
                            <th>رقم الفاتورة</th>
                            <th>المبلغ</th>
                            <th>نوع المعاملة</th>
                            <th>الوصف</th>
                            <th>معرف الخزنة</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (!empty($transactions)): ?>
                            <?php foreach ($transactions as $transaction): ?>
                                <?php
                                // استخراج رقم الفاتورة من الوصف إذا لم يكن invoice_number موجودًا
                                $invoice_number = $transaction['invoice_number'] ?? 'غير مرتبط بفاتورة';
                                if ($invoice_number === 'غير مرتبط بفاتورة' && preg_match('/فاتورة رقم (\d+)/', $transaction['description'], $matches)) {
                                    $invoice_number = $matches[1];
                                }
                                ?>
                                <tr>
                                    <td><?php echo htmlspecialchars($transaction['date']); ?></td>
                                    <td><?php echo htmlspecialchars($invoice_number); ?></td>
                                    <td><?php echo number_format($transaction['amount'], 2); ?> ج.م</td>
                                    <td class="transaction-type-<?php echo $transaction['transaction_type']; ?>">
                                        <?php
                                        switch ($transaction['transaction_type']) {
                                            case 'deposit':
                                                echo 'إيداع';
                                                break;
                                            case 'withdrawal':
                                                echo 'سحب';
                                                break;
                                            case 'income':
                                                echo 'إيراد';
                                                break;
                                            case 'pending':
                                                echo 'معلق';
                                                break;
                                            default:
                                                echo 'غير معروف';
                                        }
                                        ?>
                                    </td>
                                    <td><?php echo htmlspecialchars($transaction['description'] ?? 'لا يوجد وصف'); ?></td>
                                    <td><?php echo htmlspecialchars($transaction['treasury_id']); ?></td>
                                </tr>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <tr><td colspan="6" 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>