<?php
session_start();
include 'layouts/dbconn.php';

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

// Get user details for permission checks
$user_id = $_SESSION['user_id'];
$sql_user_details = "SELECT username, user_role, full_name, email, role_id FROM users WHERE user_id = $user_id";
$result_user_details = $conn->query($sql_user_details);

if ($result_user_details && $row_user_details = $result_user_details->fetch_assoc()) {
    $username = $row_user_details['username'];
    $user_role = $row_user_details['user_role'];
    $full_name = $row_user_details['full_name'];
    $email = $row_user_details['email'];
    $role_id = $row_user_details['role_id'];
}

// Function to check if user has admin permissions
function isAdmin($role_id) {
    return $role_id == 1 || $role_id == 2; // Admin or General Manager
}

// Function to check if user can approve requests
function canApprove($role_id) {
    // Admins, General Managers, and Finance managers can approve
    return in_array($role_id, [1, 2, 4]);
}

// Function to check if user can release funds
function canRelease($role_id) {
    // Admins, General Managers, and Finance managers can release
    return in_array($role_id, [1, 2, 4]);
}

// Format date for display
function formatDate($date) {
    if (empty($date) || $date == '0000-00-00 00:00:00') {
        return '-';
    }
    return date('Y-m-d H:i', strtotime($date));
}

// Check if request ID is provided
if (!isset($_GET['id']) || empty($_GET['id'])) {
    $_SESSION['error_message'] = "No request ID provided.";
    header('Location: fund_requests.php');
    exit();
}

$request_id = intval($_GET['id']);

// Get request details with joins
$sql = "SELECT fr.*, 
        ec.name AS category_name, 
        ec.type AS category_type,
        u1.full_name AS requester_name,
        u2.full_name AS approver_name,
        u3.full_name AS releaser_name,
        u4.full_name AS receiver_name,
        f.consignee_name, 
        f.destination
       FROM fund_requests fr
       LEFT JOIN expense_categories ec ON fr.category_id = ec.category_id
       LEFT JOIN users u1 ON fr.requested_by = u1.user_id
       LEFT JOIN users u2 ON fr.approved_by = u2.user_id
       LEFT JOIN users u3 ON fr.released_by = u3.user_id
       LEFT JOIN users u4 ON fr.received_by = u4.user_id
       LEFT JOIN files f ON fr.file_number = f.file_number
       WHERE fr.request_id = ?";

$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $request_id);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 0) {
    $_SESSION['error_message'] = "Fund request not found.";
    header('Location: fund_requests.php');
    exit();
}

$request = $result->fetch_assoc();

// Check if user has permission to view this request
// Regular users can only view their own requests
if (!isAdmin($role_id) && !canApprove($role_id) && $request['requested_by'] != $user_id) {
    $_SESSION['error_message'] = "You don't have permission to view this request.";
    header('Location: fund_requests.php');
    exit();
}

// Get request attachments if any
$attachments = [];
$sql_attachments = "SELECT * FROM fund_request_attachments WHERE request_id = ?";
$stmt_attachments = $conn->prepare($sql_attachments);
$stmt_attachments->bind_param("i", $request_id);
$stmt_attachments->execute();
$result_attachments = $stmt_attachments->get_result();

if ($result_attachments->num_rows > 0) {
    while ($row = $result_attachments->fetch_assoc()) {
        $attachments[] = $row;
    }
}

// Get request history/logs
$logs = [];
$sql_logs = "SELECT l.*, u.full_name 
             FROM fund_request_logs l
             LEFT JOIN users u ON l.performed_by = u.user_id
             WHERE l.request_id = ?
             ORDER BY l.log_date DESC";
$stmt_logs = $conn->prepare($sql_logs);
$stmt_logs->bind_param("i", $request_id);
$stmt_logs->execute();
$result_logs = $stmt_logs->get_result();

if ($result_logs->num_rows > 0) {
    while ($row = $result_logs->fetch_assoc()) {
        $logs[] = $row;
    }
}

// Get all staff for dropdown (for release modal)
$staff = [];
if (canRelease($role_id) && $request['status'] === 'Approved') {
    $staff_sql = "SELECT user_id, full_name FROM users ORDER BY full_name";
    $staff_result = $conn->query($staff_sql);
    
    if ($staff_result->num_rows > 0) {
        while ($row = $staff_result->fetch_assoc()) {
            $staff[] = $row;
        }
    }
}

// Process actions (approve, reject, release)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    $action = $_POST['action'];
    
    // Start transaction
    $conn->begin_transaction();
    
    try {
        if ($action === 'approve' && canApprove($role_id)) {
            // Approve fund request
            $sql = "UPDATE fund_requests SET 
                    status = 'Approved', 
                    approval_date = NOW(), 
                    approved_by = ? 
                    WHERE request_id = ?";
            $stmt = $conn->prepare($sql);
            $stmt->bind_param("ii", $user_id, $request_id);
            
            if (!$stmt->execute()) {
                throw new Exception("Error approving request: " . $stmt->error);
            }
            
            // Add log entry
            $log_sql = "INSERT INTO fund_request_logs (
                            request_id, action, status_from, status_to, performed_by, remarks, log_date
                        ) VALUES (?, 'Approved', 'Pending', 'Approved', ?, 'Fund request approved', NOW())";
            $log_stmt = $conn->prepare($log_sql);
            $log_stmt->bind_param("ii", $request_id, $user_id);
            $log_stmt->execute();
            
            $_SESSION['success_message'] = "Fund request approved successfully.";
            
        } elseif ($action === 'reject' && canApprove($role_id)) {
            // Reject fund request
            $rejection_reason = $_POST['rejection_reason'];
            
            $sql = "UPDATE fund_requests SET 
                    status = 'Rejected', 
                    approval_date = NOW(), 
                    approved_by = ?, 
                    rejection_reason = ? 
                    WHERE request_id = ?";
            $stmt = $conn->prepare($sql);
            $stmt->bind_param("isi", $user_id, $rejection_reason, $request_id);
            
            if (!$stmt->execute()) {
                throw new Exception("Error rejecting request: " . $stmt->error);
            }
            
            // Add log entry
            $log_sql = "INSERT INTO fund_request_logs (
                            request_id, action, status_from, status_to, performed_by, remarks, log_date
                        ) VALUES (?, 'Rejected', 'Pending', 'Rejected', ?, ?, NOW())";
            $log_stmt = $conn->prepare($log_sql);
            $log_stmt->bind_param("iis", $request_id, $user_id, $rejection_reason);
            $log_stmt->execute();
            
            $_SESSION['success_message'] = "Fund request rejected.";
            
        } elseif ($action === 'release' && canRelease($role_id)) {
            // Release funds
            $received_by = $_POST['received_by'];
            
            $sql = "UPDATE fund_requests SET 
                    status = 'Released', 
                    release_date = NOW(), 
                    released_by = ?, 
                    received_by = ? 
                    WHERE request_id = ?";
            $stmt = $conn->prepare($sql);
            $stmt->bind_param("iii", $user_id, $received_by, $request_id);
            
            if (!$stmt->execute()) {
                throw new Exception("Error releasing funds: " . $stmt->error);
            }
            
            // Add log entry
            $log_sql = "INSERT INTO fund_request_logs (
                            request_id, action, status_from, status_to, performed_by, remarks, log_date
                        ) VALUES (?, 'Released', 'Approved', 'Released', ?, 'Funds released', NOW())";
            $log_stmt = $conn->prepare($log_sql);
            $log_stmt->bind_param("ii", $request_id, $user_id);
            $log_stmt->execute();
            
            $_SESSION['success_message'] = "Funds released successfully.";
        }
        
        // Commit transaction
        $conn->commit();
        
        // Redirect to refresh page with updated data
        header('Location: view_fund_request.php?id=' . $request_id);
        exit();
        
    } catch (Exception $e) {
        // Rollback transaction
        $conn->rollback();
        $_SESSION['error_message'] = "Error: " . $e->getMessage();
        
        // Redirect to refresh
        header('Location: view_fund_request.php?id=' . $request_id);
        exit();
    }
}

// Get system name from settings
$sql_settings = "SELECT setting_value FROM settings WHERE setting_key = 'system_name'";
$result_settings = $conn->query($sql_settings);
if ($result_settings && $result_settings->num_rows > 0) {
    $row_settings = $result_settings->fetch_assoc();
    $system_name = $row_settings['setting_value'];
} else {
    $system_name = "Royal Freight Management System";
}
?>

<?php include 'layouts/main.php'; ?>
<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'View Fund Request')); ?>
    <?php include 'layouts/head-css.php'; ?>
    
    <!-- Sweet Alert css -->
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet" type="text/css" />
    
    <style>
        .request-details-card {
            margin-bottom: 1.5rem;
        }
        .details-section {
            padding: 1.5rem;
            margin-bottom: 1.5rem;
            background-color: #fff;
            border-radius: 0.25rem;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
        }
        .label-value-pair {
            margin-bottom: 1rem;
        }
        .label-value-pair .label {
            font-weight: 600;
            color: #495057;
            margin-bottom: 0.3rem;
        }
        .currency-value {
            font-family: monospace;
            font-weight: 600;
        }
        .status-badge {
            padding: 6px 10px;
            border-radius: 4px;
            font-size: 12px;
            font-weight: 500;
        }
        .timeline-item {
            position: relative;
            padding-bottom: 1.5rem;
            padding-left: 2rem;
            border-left: 2px solid #e9ecef;
        }
        .timeline-item:last-child {
            border-left-color: transparent;
            padding-bottom: 0;
        }
        .timeline-item::before {
            content: '';
            position: absolute;
            left: -0.55rem;
            top: 0;
            height: 1.1rem;
            width: 1.1rem;
            border-radius: 50%;
            background-color: #3498db;
            border: 2px solid #fff;
        }
        .timeline-date {
            font-size: 0.8rem;
            color: #6c757d;
            margin-bottom: 0.2rem;
        }
        .timeline-title {
            font-weight: 600;
        }
        .timeline-description {
            margin-top: 0.3rem;
            color: #6c757d;
        }
        .attachment-icon {
            font-size: 2rem;
            color: #6c757d;
        }
        .attachment-item {
            border: 1px solid #e9ecef;
            border-radius: 0.25rem;
            padding: 1rem;
            transition: all 0.2s;
        }
        .attachment-item:hover {
            background-color: #f8f9fa;
        }
        .print-header {
            display: none;
        }
        @media print {
            .no-print {
                display: none !important;
            }
            .print-header {
                display: block;
                text-align: center;
                margin-bottom: 20px;
            }
            .card {
                border: none !important;
                box-shadow: none !important;
            }
            .details-section {
                page-break-inside: avoid;
                box-shadow: none !important;
            }
        }
    </style>
</head>

<body>
    <!-- Begin page -->
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>

        <!-- ============================================================== -->
        <!-- Start right Content here -->
        <!-- ============================================================== -->
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <?php includeFileWithVariables('layouts/page-title.php', array('pagetitle' => 'Fund Management', 'title' => 'Fund Request Details')); ?>

                    <?php
                    // Show success message if set
                    if (isset($_SESSION['success_message'])) {
                        echo '<div class="alert alert-success alert-dismissible fade show" role="alert">';
                        echo $_SESSION['success_message'];
                        echo '<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>';
                        echo '</div>';
                        unset($_SESSION['success_message']);
                    }
                    
                    // Show error message if set
                    if (isset($_SESSION['error_message'])) {
                        echo '<div class="alert alert-danger alert-dismissible fade show" role="alert">';
                        echo $_SESSION['error_message'];
                        echo '<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>';
                        echo '</div>';
                        unset($_SESSION['error_message']);
                    }
                    ?>

                    <!-- Print header (only visible when printing) -->
                    <div class="print-header">
                        <h2><?php echo $system_name; ?></h2>
                        <h3>Fund Request Details</h3>
                        <p>Request #: <?php echo htmlspecialchars($request['request_number']); ?></p>
                    </div>

                    <div class="row">
                        <div class="col-12 mb-3 no-print">
                            <div class="d-flex justify-content-between">
                                <a href="fund_request.php" class="btn btn-secondary">
                                    <i class="ri-arrow-left-line align-bottom me-1"></i> Back to List
                                </a>
                                <div>
                                    <button type="button" class="btn btn-info me-2" onclick="window.print()">
                                        <i class="ri-printer-line align-bottom me-1"></i> Print
                                    </button>
                                    
                                    <?php if ($request['status'] === 'Pending' && canApprove($role_id)): ?>
                                    <button type="button" class="btn btn-success me-2" data-bs-toggle="modal" data-bs-target="#approveModal">
                                        <i class="ri-check-line align-bottom me-1"></i> Approve
                                    </button>
                                    <button type="button" class="btn btn-danger" data-bs-toggle="modal" data-bs-target="#rejectModal">
                                        <i class="ri-close-line align-bottom me-1"></i> Reject
                                    </button>
                                    <?php endif; ?>
                                    
                                    <?php if ($request['status'] === 'Approved' && canRelease($role_id)): ?>
                                    <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#releaseModal">
                                        <i class="ri-bank-line align-bottom me-1"></i> Release Funds
                                    </button>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>

                        <div class="col-lg-8">
                            <!-- Request Details Card -->
                            <div class="card request-details-card">
                                <div class="card-header">
                                    <h4 class="card-title mb-0">Fund Request Details</h4>
                                </div>
                                <div class="card-body">
                                    <div class="row">
                                        <div class="col-md-6">
                                            <div class="label-value-pair">
                                                <div class="label">Request Number</div>
                                                <div><?php echo htmlspecialchars($request['request_number']); ?></div>
                                            </div>
                                            
                                            <div class="label-value-pair">
                                                <div class="label">Category</div>
                                                <div>
                                                    <?php echo htmlspecialchars($request['category_name']); ?> 
                                                    <span class="badge bg-info"><?php echo htmlspecialchars($request['category_type']); ?></span>
                                                </div>
                                            </div>
                                            
                                            <div class="label-value-pair">
                                                <div class="label">Amount</div>
                                                <div class="currency-value">
                                                    <?php echo $request['currency'] == 'USD' ? '$' : 'Tsh'; ?> 
                                                    <?php echo number_format($request['amount'], 2); ?>
                                                </div>
                                            </div>
                                            
                                            <div class="label-value-pair">
                                                <div class="label">Status</div>
                                                <div>
                                                    <?php
                                                        $status_class = '';
                                                        switch ($request['status']) {
                                                            case 'Pending':
                                                                $status_class = 'bg-warning';
                                                                break;
                                                            case 'Approved':
                                                                $status_class = 'bg-info';
                                                                break;
                                                            case 'Rejected':
                                                                $status_class = 'bg-danger';
                                                                break;
                                                            case 'Released':
                                                                $status_class = 'bg-success';
                                                                break;
                                                            case 'Cancelled':
                                                                $status_class = 'bg-secondary';
                                                                break;
                                                        }
                                                    ?>
                                                    <span class="badge <?php echo $status_class; ?> status-badge">
                                                        <?php echo $request['status']; ?>
                                                    </span>
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <div class="col-md-6">
                                            <div class="label-value-pair">
                                                <div class="label">Request Date</div>
                                                <div><?php echo formatDate($request['request_date']); ?></div>
                                            </div>
                                            
                                            <div class="label-value-pair">
                                                <div class="label">Requested By</div>
                                                <div><?php echo htmlspecialchars($request['requester_name']); ?></div>
                                            </div>
                                            
                                            <?php if (!empty($request['file_number'])): ?>
                                            <div class="label-value-pair">
                                                <div class="label">File Number</div>
                                                <div>
                                                    <a href="view_file.php?id=<?php 
                                                        // Get file ID from file_number
                                                        $file_number = $request['file_number'];
                                                        $file_id_query = "SELECT id FROM files WHERE file_number = ?";
                                                        $file_id_stmt = $conn->prepare($file_id_query);
                                                        $file_id_stmt->bind_param('s', $file_number);
                                                        $file_id_stmt->execute();
                                                        $file_id_result = $file_id_stmt->get_result();
                                                        if ($file_id_row = $file_id_result->fetch_assoc()) {
                                                            echo $file_id_row['id'];
                                                        } else {
                                                            echo '0';
                                                        }
                                                    ?>" class="link-primary">
                                                        <?php echo htmlspecialchars($request['file_number']); ?>
                                                    </a>
                                                </div>
                                            </div>
                                            
                                            <?php if (!empty($request['consignee_name'])): ?>
                                            <div class="label-value-pair">
                                                <div class="label">Consignee</div>
                                                <div><?php echo htmlspecialchars($request['consignee_name']); ?></div>
                                            </div>
                                            <?php endif; ?>
                                            
                                            <?php if (!empty($request['destination'])): ?>
                                            <div class="label-value-pair">
                                                <div class="label">Destination</div>
                                                <div><?php echo htmlspecialchars($request['destination']); ?></div>
                                            </div>
                                            <?php endif; ?>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                    
                                    <div class="row mt-4">
                                        <div class="col-12">
                                            <div class="label-value-pair">
                                                <div class="label">Description/Purpose</div>
                                                <div><?php echo nl2br(htmlspecialchars($request['description'])); ?></div>
                                            </div>
                                            
                                            <?php if (!empty($request['additional_info'])): ?>
                                            <div class="label-value-pair">
                                                <div class="label">Additional Information</div>
                                                <div><?php echo nl2br(htmlspecialchars($request['additional_info'])); ?></div>
                                            </div>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- Approval & Payment Details (if applicable) -->
                            <?php if (in_array($request['status'], ['Approved', 'Rejected', 'Released'])): ?>
                            <div class="card request-details-card">
                                <div class="card-header">
                                    <h4 class="card-title mb-0">Approval & Payment Details</h4>
                                </div>
                                <div class="card-body">
                                    <?php if (in_array($request['status'], ['Approved', 'Rejected'])): ?>
                                    <div class="row">
                                        <div class="col-md-6">
                                            <div class="label-value-pair">
                                                <div class="label">
                                                    <?php echo $request['status'] === 'Approved' ? 'Approved By' : 'Rejected By'; ?>
                                                </div>
                                                <div><?php echo htmlspecialchars($request['approver_name']); ?></div>
                                            </div>
                                            
                                            <div class="label-value-pair">
                                                <div class="label">
                                                    <?php echo $request['status'] === 'Approved' ? 'Approval Date' : 'Rejection Date'; ?>
                                                </div>
                                                <div><?php echo formatDate($request['approval_date']); ?></div>
                                            </div>
                                        </div>
                                        
                                        <?php if ($request['status'] === 'Rejected' && !empty($request['rejection_reason'])): ?>
                                        <div class="col-md-6">
                                            <div class="label-value-pair">
                                                <div class="label">Rejection Reason</div>
                                                <div><?php echo nl2br(htmlspecialchars($request['rejection_reason'])); ?></div>
                                            </div>
                                        </div>
                                        <?php endif; ?>
                                    </div>
                                    <?php endif; ?>
                                    
                                    <?php if ($request['status'] === 'Released'): ?>
                                    <div class="row mt-3">
                                        <div class="col-md-6">
                                            <div class="label-value-pair">
                                                <div class="label">Released By</div>
                                                <div><?php echo htmlspecialchars($request['releaser_name']); ?></div>
                                            </div>
                                            
                                            <div class="label-value-pair">
                                                <div class="label">Release Date</div>
                                                <div><?php echo formatDate($request['release_date']); ?></div>
                                            </div>
                                        </div>
                                        
                                        <div class="col-md-6">
                                            <div class="label-value-pair">
                                                <div class="label">Released To</div>
                                                <div><?php echo htmlspecialchars($request['receiver_name']); ?></div>
                                            </div>
                                        </div>
                                    </div>
                                    <?php endif; ?>
                                </div>
                            </div>
                            <?php endif; ?>
                            
                            <!-- Attachments Section (if any) -->
                            <?php if (!empty($attachments)): ?>
                            <div class="card request-details-card">
                                <div class="card-header">
                                    <h4 class="card-title mb-0">Attachments</h4>
                                </div>
                                <div class="card-body">
                                    <div class="row">
                                        <?php foreach ($attachments as $attachment): ?>
                                        <div class="col-md-6 col-lg-4 mb-3">
                                            <div class="attachment-item">
                                                <div class="d-flex align-items-center">
                                                    <div class="flex-shrink-0">
                                                        <?php
                                                        $file_ext = pathinfo($attachment['file_name'], PATHINFO_EXTENSION);
                                                        $icon_class = 'ri-file-text-line';
                                                        
                                                        if (in_array(strtolower($file_ext), ['jpg', 'jpeg', 'png', 'gif'])) {
                                                            $icon_class = 'ri-image-line';
                                                        } elseif (in_array(strtolower($file_ext), ['pdf'])) {
                                                            $icon_class = 'ri-file-pdf-line';
                                                        } elseif (in_array(strtolower($file_ext), ['doc', 'docx'])) {
                                                            $icon_class = 'ri-file-word-line';
                                                        } elseif (in_array(strtolower($file_ext), ['xls', 'xlsx'])) {
                                                            $icon_class = 'ri-file-excel-line';
                                                        }
                                                        ?>
                                                        <i class="<?php echo $icon_class; ?> attachment-icon"></i>
                                                    </div>
                                                    <div class="flex-grow-1 ms-3">
                                                        <h5 class="fs-14 mb-1"><?php echo htmlspecialchars($attachment['file_name']); ?></h5>
                                                        <p class="text-muted mb-0">
                                                            <?php echo strtoupper($file_ext); ?>, 
                                                            <?php echo round($attachment['file_size'] / 1024, 1); ?> KB
                                                        </p>
                                                    </div>
                                                    <div class="flex-shrink-0">
                                                        <a href="<?php echo htmlspecialchars($attachment['file_path']); ?>" class="btn btn-sm btn-soft-primary" download>
                                                            <i class="ri-download-line"></i>
                                                        </a>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                        <?php endforeach; ?>
                                    </div>
                                </div>
                            </div>
                            <?php endif; ?>
                        </div>
                        
                        <div class="col-lg-4">
                            <!-- Status Timeline -->
                            <div class="card request-details-card">
                                <div class="card-header">
                                    <h4 class="card-title mb-0">Request Timeline</h4>
                                </div>
                                <div class="card-body">
                                    <?php if (!empty($logs)): ?>
                                    <div class="timeline mt-3">
                                        <?php foreach ($logs as $log): ?>
                                        <div class="timeline-item">
                                            <div class="timeline-date"><?php echo formatDate($log['log_date']); ?></div>
                                            <div class="timeline-title">
                                                <?php
                                                $action_badge_class = 'bg-primary';
                                                switch ($log['action']) {
                                                    case 'Created':
                                                        $action_badge_class = 'bg-info';
                                                        break;
                                                    case 'Updated':
                                                        $action_badge_class = 'bg-warning';
                                                        break;
                                                    case 'Approved':
                                                        $action_badge_class = 'bg-success';
                                                        break;
                                                    case 'Rejected':
                                                        $action_badge_class = 'bg-danger';
                                                        break;
                                                    case 'Released':
                                                        $action_badge_class = 'bg-primary';
                                                        break;
                                                    default:
                                                        $action_badge_class = 'bg-secondary';
                                                }
                                                ?>
                                                <span class="badge <?php echo $action_badge_class; ?>"><?php echo $log['action']; ?></span>
                                                by <?php echo htmlspecialchars($log['full_name']); ?>
                                            </div>
                                            <?php if (!empty($log['remarks'])): ?>
                                            <div class="timeline-description">
                                                <?php echo htmlspecialchars($log['remarks']); ?>
                                            </div>
                                            <?php endif; ?>
                                        </div>
                                        <?php endforeach; ?>
                                        
                                        <!-- Initial creation (if not in logs) -->
                                        <?php if (!array_filter($logs, function($log) { return $log['action'] === 'Created'; })): ?>
                                        <div class="timeline-item">
                                            <div class="timeline-date"><?php echo formatDate($request['request_date']); ?></div>
                                            <div class="timeline-title">
                                                <span class="badge bg-info">Created</span>
                                                by <?php echo htmlspecialchars($request['requester_name']); ?>
                                            </div>
                                            <div class="timeline-description">
                                                Fund request created
                                            </div>
                                        </div>
                                        <?php endif; ?>
                                    </div>
                                    <?php else: ?>
                                    <div class="timeline mt-3">
                                        <div class="timeline-item">
                                            <div class="timeline-date"><?php echo formatDate($request['request_date']); ?></div>
                                            <div class="timeline-title">
                                                <span class="badge bg-info">Created</span>
                                                by <?php echo htmlspecialchars($request['requester_name']); ?>
                                            </div>
                                            <div class="timeline-description">
                                                Fund request created
                                            </div>
                                        </div>
                                    </div>
                                    <?php endif; ?>
                                </div>
                            </div>
                            
                            <!-- Quick Actions Card -->
                            <div class="card request-details-card no-print">
                                <div class="card-header">
                                    <h4 class="card-title mb-0">Quick Actions</h4>
                                </div>
                                <div class="card-body">
                                    <div class="d-grid gap-2">
                                        <a href="fund_request.php" class="btn btn-outline-secondary">
                                            <i class="ri-arrow-left-line align-bottom me-1"></i> Back to List
                                        </a>
                                        
                                        <button type="button" class="btn btn-outline-info" onclick="window.print()">
                                            <i class="ri-printer-line align-bottom me-1"></i> Print Details
                                        </button>
                                        
                                        <?php if ($request['status'] === 'Pending' && canApprove($role_id)): ?>
                                        <button type="button" class="btn btn-success" data-bs-toggle="modal" data-bs-target="#approveModal">
                                            <i class="ri-check-line align-bottom me-1"></i> Approve Request
                                        </button>
                                        
                                        <button type="button" class="btn btn-danger" data-bs-toggle="modal" data-bs-target="#rejectModal">
                                            <i class="ri-close-line align-bottom me-1"></i> Reject Request
                                        </button>
                                        <?php endif; ?>
                                        
                                        <?php if ($request['status'] === 'Approved' && canRelease($role_id)): ?>
                                        <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#releaseModal">
                                            <i class="ri-bank-line align-bottom me-1"></i> Release Funds
                                        </button>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <!-- container-fluid -->
            </div>
            <!-- End Page-content -->

            <?php include 'layouts/footer.php'; ?>
        </div>
        <!-- end main content-->
    </div>
    <!-- END layout-wrapper -->

    <!-- Approve Modal -->
    <?php if ($request['status'] === 'Pending' && canApprove($role_id)): ?>
    <div class="modal fade" id="approveModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header bg-light p-3">
                    <h5 class="modal-title">Approve Fund Request</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <form action="" method="POST">
                    <div class="modal-body">
                        <p>Are you sure you want to approve this fund request for 
                            <strong><?php echo $request['currency'] == 'USD' ? '$' : 'Tsh'; ?> <?php echo number_format($request['amount'], 2); ?></strong>?</p>
                        <input type="hidden" name="action" value="approve">
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-light" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-success">Approve</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Reject Modal -->
    <div class="modal fade" id="rejectModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header bg-light p-3">
                    <h5 class="modal-title">Reject Fund Request</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <form action="" method="POST">
                    <div class="modal-body">
                        <p>Are you sure you want to reject this fund request?</p>
                        <div class="mb-3">
                            <label for="rejection-reason" class="form-label">Reason for Rejection</label>
                            <textarea class="form-control" id="rejection-reason" name="rejection_reason" rows="3" required></textarea>
                        </div>
                        <input type="hidden" name="action" value="reject">
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-light" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-danger">Reject</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
    <?php endif; ?>

    <!-- Release Funds Modal -->
    <?php if ($request['status'] === 'Approved' && canRelease($role_id)): ?>
    <div class="modal fade" id="releaseModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header bg-light p-3">
                    <h5 class="modal-title">Release Funds</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <form action="" method="POST">
                    <div class="modal-body">
                        <p>You are about to release <strong><?php echo $request['currency'] == 'USD' ? '$' : 'Tsh'; ?> <?php echo number_format($request['amount'], 2); ?></strong> for this request.</p>
                        
                        <div class="mb-3">
                            <label for="received-by" class="form-label">Received By</label>
                            <select class="form-select" id="received-by" name="received_by" required>
                                <option value="">Select Staff Member</option>
                                <?php foreach ($staff as $member): ?>
                                <option value="<?php echo $member['user_id']; ?>"><?php echo htmlspecialchars($member['full_name']); ?></option>
                                <?php endforeach; ?>
                            </select>
                            <div class="form-text">Select the staff member who will receive the funds</div>
                        </div>
                        
                        <input type="hidden" name="action" value="release">
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-light" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-primary">Release Funds</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
    <?php endif; ?>

    <?php include 'layouts/vendor-scripts.php'; ?>
    
    <!-- Sweet Alerts js -->
    <script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>
    
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // Show success message with SweetAlert if present
            <?php if (isset($_SESSION['swal_success'])): ?>
            Swal.fire({
                icon: 'success',
                title: 'Success!',
                text: '<?php echo $_SESSION['swal_success']; ?>',
                confirmButtonColor: '#3085d6'
            });
            <?php unset($_SESSION['swal_success']); endif; ?>
            
            // Show error message with SweetAlert if present
            <?php if (isset($_SESSION['swal_error'])): ?>
            Swal.fire({
                icon: 'error',
                title: 'Error',
                text: '<?php echo $_SESSION['swal_error']; ?>',
                confirmButtonColor: '#3085d6'
            });
            <?php unset($_SESSION['swal_error']); endif; ?>
        });
    </script>

    <script src="assets/js/app.js"></script>
</body>
</html>