<?php
require_once 'config/init.php';
require_once 'includes/auth.php';
requireAuth();

// Enable error reporting for debugging
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('log_errors', 1);
ini_set('error_log', __DIR__ . '/error.log');

$db = getDB();

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        $db->exec('BEGIN TRANSACTION');
        
        if (isset($_POST['action'])) {
            switch ($_POST['action']) {
                case 'create':
                    $initial_balance = floatval($_POST['initial_balance']);
                    if ($initial_balance < 0) {
                        throw new Exception("الرصيد الأساسي لا يمكن أن يكون سالباً");
                    }
                    
                    $stmt = $db->prepare("INSERT INTO cash_fund (initial_balance, current_balance, created_at, updated_at) VALUES (:initial_balance, :current_balance, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)");
                    $stmt->bindValue(':initial_balance', $initial_balance, SQLITE3_FLOAT);
                    $stmt->bindValue(':current_balance', $initial_balance, SQLITE3_FLOAT);
                    
                    if (!$stmt->execute()) {
                        throw new Exception("فشل في إنشاء الصندوق المالي");
                    }
                    $_SESSION['success_message'] = "تم إنشاء الصندوق المالي بنجاح";
                    break;
                
                case 'update':
                    $id = filter_var($_POST['fund_id'], FILTER_VALIDATE_INT);
                    $current_balance = floatval($_POST['current_balance']);
                    
                    if (!$id) {
                        throw new Exception("معرف الصندوق غير صالح");
                    }
                    
                    $stmt = $db->prepare("UPDATE cash_fund SET current_balance = :current_balance, updated_at = CURRENT_TIMESTAMP WHERE id = :id");
                    $stmt->bindValue(':current_balance', $current_balance, SQLITE3_FLOAT);
                    $stmt->bindValue(':id', $id, SQLITE3_INTEGER);
                    
                    if (!$stmt->execute()) {
                        throw new Exception("فشل في تحديث رصيد الصندوق");
                    }
                    $_SESSION['success_message'] = "تم تحديث رصيد الصندوق بنجاح";
                    break;
                
                case 'delete':
                    // Check if there are any pending transactions
                    $stmt = $db->prepare("SELECT COUNT(*) as count FROM financial_transactions WHERE source_type = 'CASH_FUND' OR destination_type = 'CASH_FUND'");
                    $result = $stmt->execute();
                    $row = $result->fetchArray(SQLITE3_ASSOC);
                    
                    if ($row['count'] > 0) {
                        throw new Exception("لا يمكن حذف الصندوق لوجود معاملات مرتبطة به");
                    }
                    
                    $id = filter_var($_POST['fund_id'], FILTER_VALIDATE_INT);
                    if (!$id) {
                        throw new Exception("معرف الصندوق غير صالح");
                    }
                    
                    $stmt = $db->prepare("DELETE FROM cash_fund WHERE id = :id");
                    $stmt->bindValue(':id', $id, SQLITE3_INTEGER);
                    
                    if (!$stmt->execute()) {
                        throw new Exception("فشل في حذف الصندوق");
                    }
                    $_SESSION['success_message'] = "تم حذف الصندوق بنجاح";
                    break;
            }
        }
        $db->exec('COMMIT');
        header('Location: cash_fund.php');
        exit;
    } catch (Exception $e) {
        $db->exec('ROLLBACK');
        $_SESSION['error_message'] = $e->getMessage();
        header('Location: cash_fund.php');
        exit;
    }
}

// Get cash fund data
$stmt = $db->prepare("SELECT * FROM cash_fund ORDER BY id DESC LIMIT 1");
$result = $stmt->execute();
$cash_fund = $result->fetchArray(SQLITE3_ASSOC);

// Get recent transactions
$stmt = $db->prepare("
    SELECT 
        ft.*,
        CASE 
            WHEN reference_type = 'INVOICE' THEN (SELECT 'فاتورة رقم ' || invoice_number FROM invoices WHERE id = ft.reference_id)
            WHEN reference_type = 'DEBT' THEN (SELECT 'دين رقم ' || id FROM subscriber_debts WHERE id = ft.reference_id)
            ELSE description
        END as reference_details
    FROM financial_transactions ft
    WHERE source_type = 'CASH_FUND' OR destination_type = 'CASH_FUND'
    ORDER BY created_at DESC
    LIMIT 50
");
$result = $stmt->execute();
$transactions = [];
while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
    $transactions[] = $row;
}

require_once 'includes/header.php';
?>

<div class="container-fluid">
    <div class="row">
        <?php require_once 'includes/sidebar.php'; ?>
        
        <main class="col-md-9 ms-sm-auto col-lg-10 px-md-4">
            <h2 class="my-4">إدارة الصندوق المالي</h2>
            
            <?php if (isset($_SESSION['error_message'])): ?>
                <div class="alert alert-danger alert-dismissible fade show" role="alert">
                    <?= htmlspecialchars($_SESSION['error_message']) ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                </div>
                <?php unset($_SESSION['error_message']); ?>
            <?php endif; ?>

            <?php if (isset($_SESSION['success_message'])): ?>
                <div class="alert alert-success alert-dismissible fade show" role="alert">
                    <?= htmlspecialchars($_SESSION['success_message']) ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                </div>
                <?php unset($_SESSION['success_message']); ?>
            <?php endif; ?>
            
            <?php if (!$cash_fund): ?>
            <!-- Create Cash Fund Form -->
            <div class="card mb-4">
                <div class="card-header">
                    <h4>إنشاء صندوق مالي جديد</h4>
                </div>
                <div class="card-body">
                    <form method="POST">
                        <input type="hidden" name="action" value="create">
                        <div class="form-group">
                            <label>الرصيد الأساسي (درهم)</label>
                            <input type="number" step="0.01" name="initial_balance" class="form-control" required>
                        </div>
                        <button type="submit" class="btn btn-primary mt-3">إنشاء</button>
                    </form>
                </div>
            </div>
            <?php else: ?>
            <!-- Display Cash Fund Info -->
            <div class="card mb-4">
                <div class="card-header">
                    <h4>حالة الصندوق</h4>
                </div>
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-6">
                            <p><strong>الرصيد الأساسي:</strong> <?= number_format($cash_fund['initial_balance'], 2) ?> درهم</p>
                            <p><strong>الرصيد الحالي:</strong> <span class="<?= $cash_fund['current_balance'] < 0 ? 'text-danger' : 'text-success' ?>"><?= number_format($cash_fund['current_balance'], 2) ?> درهم</span></p>
                            <p><strong>آخر تحديث:</strong> <?= date('Y-m-d H:i:s', strtotime($cash_fund['updated_at'])) ?></p>
                        </div>
                        <div class="col-md-6 text-end">
                            <form method="POST" class="d-inline">
                                <input type="hidden" name="action" value="delete">
                                <input type="hidden" name="fund_id" value="<?= $cash_fund['id'] ?>">
                                <button type="submit" class="btn btn-danger" onclick="return confirm('تحذير: سيؤدي حذف الصندوق إلى حذف جميع السجلات المرتبطة به. هل أنت متأكد من المتابعة؟')">
                                    حذف الصندوق
                                </button>
                            </form>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Transactions History -->
            <div class="card">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <h4>سجل العمليات</h4>
                    <div class="transaction-summary">
                        <span class="badge bg-success me-2">إجمالي الإيداعات: <?= number_format(array_reduce($transactions, function($carry, $trans) {
                            return $carry + ($trans['transaction_type'] === 'DEPOSIT' ? $trans['amount'] : 0);
                        }, 0), 2) ?> درهم</span>
                        <span class="badge bg-danger">إجمالي السحوبات: <?= number_format(array_reduce($transactions, function($carry, $trans) {
                            return $carry + ($trans['transaction_type'] === 'WITHDRAWAL' ? $trans['amount'] : 0);
                        }, 0), 2) ?> درهم</span>
                    </div>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-striped">
                            <thead>
                                <tr>
                                    <th>التاريخ</th>
                                    <th>نوع العملية</th>
                                    <th>المبلغ (درهم)</th>
                                    <th>الوصف</th>
                                    <th>المرجع</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($transactions as $trans): ?>
                                <tr>
                                    <td><?= date('Y-m-d', strtotime($trans['created_at'])) ?></td>
                                    <td>
                                        <span class="badge <?= $trans['transaction_type'] === 'DEPOSIT' ? 'bg-success' : 'bg-danger' ?>">
                                            <?= $trans['transaction_type'] === 'DEPOSIT' ? 'إيداع' : 'سحب' ?>
                                        </span>
                                    </td>
                                    <td><?= number_format($trans['amount'], 2) ?></td>
                                    <td><?= htmlspecialchars($trans['description']) ?></td>
                                    <td><?= htmlspecialchars($trans['reference_details']) ?></td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
            <?php endif; ?>
        </main>
    </div>
</div>

<?php require_once 'includes/footer.php'; ?>
