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

// Set timezone to East Africa Time
date_default_timezone_set('Africa/Nairobi');

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

// Get expense ID from URL
$expense_id = $_GET['id'] ?? 0;

if (!$expense_id) {
    header('Location: list_expenses.php');
    exit();
}

// Fetch user details
$user_id = $_SESSION['user_id'];
$sql_user_details = "SELECT u.*, ur.role_name FROM users u 
                     INNER JOIN user_roles ur ON u.role_id = ur.role_id 
                     WHERE u.user_id = ?";
$stmt_user = $conn->prepare($sql_user_details);
$stmt_user->bind_param("i", $user_id);
$stmt_user->execute();
$user_details = $stmt_user->get_result()->fetch_assoc();

if ($user_details) {
    $username = $user_details['username'];
    $role_name = $user_details['role_name'];
    $full_name = $user_details['full_name'];
    $email = $user_details['email'];
}

// Get expense details with all related information
$expense_query = "SELECT e.*, 
                         ec.category_name, ec.category_type, ec.color_code, ec.requires_approval,
                         u_created.full_name as created_by_name, u_created.email as created_by_email,
                         u_approved.full_name as approved_by_name,
                         u_paid.full_name as paid_by_name,
                         f.fund_name, f.current_balance as fund_balance
                  FROM expenses e
                  LEFT JOIN expense_categories ec ON e.category_id = ec.category_id
                  LEFT JOIN users u_created ON e.created_by = u_created.user_id
                  LEFT JOIN users u_approved ON e.approved_by = u_approved.user_id
                  LEFT JOIN users u_paid ON e.paid_by = u_paid.user_id
                  LEFT JOIN funds f ON e.fund_id = f.fund_id
                  WHERE e.expense_id = ?";

$stmt = $conn->prepare($expense_query);
$stmt->bind_param("i", $expense_id);
$stmt->execute();
$expense = $stmt->get_result()->fetch_assoc();

if (!$expense) {
    header('Location: list_expenses.php?error=expense_not_found');
    exit();
}

// Get expense attachments
$attachments_query = "SELECT * FROM expense_attachments WHERE expense_id = ? ORDER BY uploaded_at DESC";
$attachments_stmt = $conn->prepare($attachments_query);
$attachments_stmt->bind_param("i", $expense_id);
$attachments_stmt->execute();
$attachments = $attachments_stmt->get_result();

// Get expense comments/notes
$comments_query = "SELECT ec.*, u.full_name as user_name 
                   FROM expense_comments ec
                   LEFT JOIN users u ON ec.user_id = u.user_id
                   WHERE ec.expense_id = ?
                   ORDER BY ec.created_at DESC";
$comments_stmt = $conn->prepare($comments_query);
$comments_stmt->bind_param("i", $expense_id);
$comments_stmt->execute();
$comments = $comments_stmt->get_result();

// Get approval history if exists
$approval_query = "SELECT ea.*, 
                          u_requested.full_name as requested_by_name,
                          u_reviewed.full_name as reviewed_by_name
                   FROM expense_approvals ea
                   LEFT JOIN users u_requested ON ea.requested_by = u_requested.user_id
                   LEFT JOIN users u_reviewed ON ea.reviewed_by = u_reviewed.user_id
                   WHERE ea.expense_id = ?
                   ORDER BY ea.requested_at DESC";
$approval_stmt = $conn->prepare($approval_query);
$approval_stmt->bind_param("i", $expense_id);
$approval_stmt->execute();
$approvals = $approval_stmt->get_result();

// Handle comment submission
$success_message = '';
$error_message = '';

if ($_POST && isset($_POST['add_comment'])) {
    $comment_text = trim($_POST['comment_text']);
    $comment_type = $_POST['comment_type'] ?? 'GENERAL';
    $is_internal = isset($_POST['is_internal']) ? 1 : 0;
    
    if (!empty($comment_text)) {
        $comment_insert = "INSERT INTO expense_comments (expense_id, user_id, comment_text, comment_type, is_internal) VALUES (?, ?, ?, ?, ?)";
        $comment_stmt = $conn->prepare($comment_insert);
        $comment_stmt->bind_param("iissi", $expense_id, $user_id, $comment_text, $comment_type, $is_internal);
        
        if ($comment_stmt->execute()) {
            $success_message = "Comment added successfully!";
            // Refresh comments
            $comments_stmt->execute();
            $comments = $comments_stmt->get_result();
        } else {
            $error_message = "Failed to add comment.";
        }
    }
}

// Handle AJAX actions
if ($_POST && isset($_POST['action'])) {
    header('Content-Type: application/json');
    
    $action = $_POST['action'];
    $response = ['success' => false, 'message' => ''];
    
    switch ($action) {
        case 'approve_expense':
            if (in_array($role_name, ['Administrator', 'Fund Manager'])) {
                $update_query = "UPDATE expenses SET status = 'APPROVED', approved_by = ?, approved_at = NOW() WHERE expense_id = ?";
                $update_stmt = $conn->prepare($update_query);
                $update_stmt->bind_param("ii", $user_id, $expense_id);
                
                if ($update_stmt->execute()) {
                    $response['success'] = true;
                    $response['message'] = 'Expense approved successfully!';
                } else {
                    $response['message'] = 'Failed to approve expense.';
                }
            } else {
                $response['message'] = 'You do not have permission to approve expenses.';
            }
            break;
            
        case 'reject_expense':
            if (in_array($role_name, ['Administrator', 'Fund Manager'])) {
                $reason = $_POST['reason'] ?? '';
                $update_query = "UPDATE expenses SET status = 'REJECTED', notes = CONCAT(COALESCE(notes, ''), '\nRejected: ', ?) WHERE expense_id = ?";
                $update_stmt = $conn->prepare($update_query);
                $update_stmt->bind_param("si", $reason, $expense_id);
                
                if ($update_stmt->execute()) {
                    $response['success'] = true;
                    $response['message'] = 'Expense rejected successfully!';
                } else {
                    $response['message'] = 'Failed to reject expense.';
                }
            } else {
                $response['message'] = 'You do not have permission to reject expenses.';
            }
            break;
            
        case 'mark_paid':
            if (in_array($role_name, ['Administrator', 'Fund Manager'])) {
                $update_query = "UPDATE expenses SET status = 'PAID', paid_by = ?, paid_at = NOW() WHERE expense_id = ?";
                $update_stmt = $conn->prepare($update_query);
                $update_stmt->bind_param("ii", $user_id, $expense_id);
                
                if ($update_stmt->execute()) {
                    $response['success'] = true;
                    $response['message'] = 'Expense marked as paid successfully!';
                } else {
                    $response['message'] = 'Failed to mark expense as paid.';
                }
            } else {
                $response['message'] = 'You do not have permission to mark expenses as paid.';
            }
            break;
            
        case 'delete_expense':
            if (in_array($role_name, ['Administrator']) && in_array($expense['status'], ['DRAFT', 'REJECTED'])) {
                $delete_query = "DELETE FROM expenses WHERE expense_id = ?";
                $delete_stmt = $conn->prepare($delete_query);
                $delete_stmt->bind_param("i", $expense_id);
                
                if ($delete_stmt->execute()) {
                    $response['success'] = true;
                    $response['message'] = 'Expense deleted successfully!';
                    $response['redirect'] = 'list_expenses.php';
                } else {
                    $response['message'] = 'Failed to delete expense.';
                }
            } else {
                $response['message'] = 'You do not have permission to delete this expense or it cannot be deleted in its current status.';
            }
            break;
    }
    
    echo json_encode($response);
    exit();
}
?>

<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'View Expense - Personal Fund Management System')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/sweetalert2@11.7.32/dist/sweetalert2.min.css" rel="stylesheet">
    
    <style>
        body {
            background-color: #f8fafc;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
        }
        
        .page-content {
            padding: 1.5rem;
        }
        
        /* Page Header */
        .page-header {
            background: linear-gradient(135deg, #6366f1 0%, #8b5cf6 100%);
            color: white;
            border-radius: 12px;
            padding: 2rem;
            margin-bottom: 2rem;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
        }
        
        .page-title {
            font-size: 1.75rem;
            font-weight: 600;
            margin-bottom: 0.5rem;
        }
        
        .page-subtitle {
            opacity: 0.9;
            margin: 0;
        }
        
        /* Cards */
        .info-card {
            background: white;
            border-radius: 12px;
            padding: 1.5rem;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
            margin-bottom: 1.5rem;
        }
        
        .card-title {
            font-size: 1.125rem;
            font-weight: 600;
            color: #1e293b;
            margin-bottom: 1rem;
            padding-bottom: 0.5rem;
            border-bottom: 2px solid #e2e8f0;
        }
        
        /* Status Badges */
        .status-badge {
            padding: 0.5rem 1rem;
            border-radius: 8px;
            font-size: 0.875rem;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.05em;
            display: inline-block;
        }
        
        .status-draft { background: #f1f5f9; color: #64748b; }
        .status-pending { background: #fef3c7; color: #92400e; }
        .status-approved { background: #dcfce7; color: #166534; }
        .status-paid { background: #dcfce7; color: #166534; }
        .status-rejected { background: #fee2e2; color: #991b1b; }
        .status-cancelled { background: #fee2e2; color: #991b1b; }
        
        /* Category Type Badges */
        .type-badge {
            padding: 0.5rem 1rem;
            border-radius: 8px;
            font-size: 0.875rem;
            font-weight: 500;
            display: inline-block;
        }
        
        .type-shop { background: #fee2e2; color: #991b1b; }
        .type-company { background: #dbeafe; color: #1e40af; }
        .type-family { background: #dcfce7; color: #166534; }
        
        /* Payment Method Badges */
        .payment-badge {
            padding: 0.5rem 1rem;
            border-radius: 8px;
            font-size: 0.875rem;
            font-weight: 500;
            display: inline-block;
        }
        
        .payment-cash { background: #dcfce7; color: #166534; }
        .payment-card { background: #ddd6fe; color: #5b21b6; }
        .payment-bank-transfer { background: #e0e7ff; color: #3730a3; }
        .payment-mpesa { background: #fef3c7; color: #92400e; }
        .payment-mobile-money { background: #fef3c7; color: #92400e; }
        .payment-cheque { background: #f3e8ff; color: #7c3aed; }
        
        /* Info Rows */
        .info-row {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 0.75rem 0;
            border-bottom: 1px solid #f1f5f9;
        }
        
        .info-row:last-child {
            border-bottom: none;
        }
        
        .info-label {
            font-weight: 600;
            color: #64748b;
            min-width: 150px;
        }
        
        .info-value {
            color: #1e293b;
            font-weight: 500;
        }
        
        /* Amount Display */
        .amount-display {
            font-size: 2rem;
            font-weight: 700;
            color: #059669;
            text-align: center;
            padding: 1rem;
            background: #f0fdf4;
            border-radius: 8px;
            border: 2px solid #bbf7d0;
        }
        
        /* Action Buttons */
        .action-buttons {
            display: flex;
            gap: 1rem;
            flex-wrap: wrap;
            margin: 1.5rem 0;
        }
        
        .btn {
            padding: 0.75rem 1.5rem;
            border-radius: 8px;
            font-weight: 600;
            font-size: 0.875rem;
            border: none;
            cursor: pointer;
            transition: all 0.2s ease;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 0.5rem;
        }
        
        .btn-primary { background: #3b82f6; color: white; }
        .btn-primary:hover { background: #1d4ed8; color: white; }
        
        .btn-success { background: #059669; color: white; }
        .btn-success:hover { background: #047857; color: white; }
        
        .btn-warning { background: #d97706; color: white; }
        .btn-warning:hover { background: #b45309; color: white; }
        
        .btn-danger { background: #dc2626; color: white; }
        .btn-danger:hover { background: #b91c1c; color: white; }
        
        .btn-secondary { background: #6b7280; color: white; }
        .btn-secondary:hover { background: #4b5563; color: white; }
        
        /* Timeline */
        .timeline {
            position: relative;
            padding-left: 2rem;
        }
        
        .timeline::before {
            content: '';
            position: absolute;
            left: 0.75rem;
            top: 0;
            bottom: 0;
            width: 2px;
            background: #e2e8f0;
        }
        
        .timeline-item {
            position: relative;
            margin-bottom: 1.5rem;
        }
        
        .timeline-item::before {
            content: '';
            position: absolute;
            left: -0.625rem;
            top: 0.5rem;
            width: 0.75rem;
            height: 0.75rem;
            background: #059669;
            border-radius: 50%;
        }
        
        .timeline-content {
            background: #f8fafc;
            padding: 1rem;
            border-radius: 8px;
            border-left: 3px solid #059669;
        }
        
        .timeline-date {
            font-size: 0.75rem;
            color: #64748b;
            margin-bottom: 0.5rem;
        }
        
        .timeline-title {
            font-weight: 600;
            color: #1e293b;
            margin-bottom: 0.25rem;
        }
        
        .timeline-description {
            color: #64748b;
            font-size: 0.875rem;
        }
        
        /* Comments */
        .comment {
            background: #f8fafc;
            border-radius: 8px;
            padding: 1rem;
            margin-bottom: 1rem;
            border-left: 3px solid #6366f1;
        }
        
        .comment-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 0.5rem;
        }
        
        .comment-author {
            font-weight: 600;
            color: #1e293b;
        }
        
        .comment-date {
            font-size: 0.75rem;
            color: #64748b;
        }
        
        .comment-text {
            color: #374151;
            line-height: 1.5;
        }
        
        /* Form Controls */
        .form-control, .form-select {
            border: 1px solid #e2e8f0;
            border-radius: 8px;
            padding: 0.75rem;
            font-size: 0.875rem;
        }
        
        .form-control:focus, .form-select:focus {
            border-color: #6366f1;
            box-shadow: 0 0 0 3px rgba(99, 102, 241, 0.1);
        }
        
        /* Alert Messages */
        .alert {
            border-radius: 8px;
            padding: 1rem;
            margin-bottom: 1.5rem;
            border: none;
        }
        
        .alert-success {
            background: #dcfce7;
            color: #166534;
        }
        
        .alert-danger {
            background: #fee2e2;
            color: #991b1b;
        }
        
        /* Attachments */
        .attachment {
            display: flex;
            align-items: center;
            gap: 1rem;
            padding: 1rem;
            background: #f8fafc;
            border-radius: 8px;
            margin-bottom: 0.5rem;
        }
        
        .attachment-icon {
            width: 40px;
            height: 40px;
            background: #6366f1;
            color: white;
            border-radius: 8px;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        
        .attachment-info {
            flex: 1;
        }
        
        .attachment-name {
            font-weight: 600;
            color: #1e293b;
        }
        
        .attachment-meta {
            font-size: 0.75rem;
            color: #64748b;
        }
        
        /* Responsive */
        @media (max-width: 768px) {
            .page-content {
                padding: 1rem;
            }
            
            .action-buttons {
                flex-direction: column;
            }
            
            .info-row {
                flex-direction: column;
                align-items: flex-start;
                gap: 0.5rem;
            }
            
            .amount-display {
                font-size: 1.5rem;
            }
        }
    </style>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <!-- Page Header -->
                    <div class="page-header">
                        <h1 class="page-title">Expense Details</h1>
                        <p class="page-subtitle">Expense #<?php echo htmlspecialchars($expense['expense_number']); ?></p>
                    </div>

                    <!-- Success/Error Messages -->
                    <?php if ($success_message): ?>
                        <div class="alert alert-success">
                            <i class="ph-check-circle me-2"></i>
                            <?php echo htmlspecialchars($success_message); ?>
                        </div>
                    <?php endif; ?>

                    <?php if ($error_message): ?>
                        <div class="alert alert-danger">
                            <i class="ph-warning-circle me-2"></i>
                            <?php echo htmlspecialchars($error_message); ?>
                        </div>
                    <?php endif; ?>

                    <div class="row">
                        <!-- Main Expense Information -->
                        <div class="col-lg-8">
                            <!-- Basic Information -->
                            <div class="info-card">
                                <h3 class="card-title">
                                    <i class="ph-receipt me-2"></i>
                                    <?php echo htmlspecialchars($expense['expense_title']); ?>
                                </h3>
                                
                                <div class="amount-display">
                                    KES <?php echo number_format($expense['amount'], 2); ?>
                                </div>
                                
                                <div class="text-center mt-3 mb-3">
                                    <?php 
                                    $status_class = match($expense['status']) {
                                        'DRAFT' => 'status-draft',
                                        'PENDING' => 'status-pending',
                                        'APPROVED' => 'status-approved',
                                        'PAID' => 'status-paid',
                                        'REJECTED' => 'status-rejected',
                                        'CANCELLED' => 'status-cancelled',
                                        default => 'status-draft'
                                    };
                                    ?>
                                    <span class="status-badge <?php echo $status_class; ?>">
                                        <?php echo ucfirst(str_replace('_', ' ', strtolower($expense['status']))); ?>
                                    </span>
                                </div>
                                
                                <?php if ($expense['description']): ?>
                                    <div class="mt-3">
                                        <h6 style="color: #64748b; margin-bottom: 0.5rem;">Description:</h6>
                                        <p style="color: #374151; line-height: 1.6; margin: 0;">
                                            <?php echo nl2br(htmlspecialchars($expense['description'])); ?>
                                        </p>
                                    </div>
                                <?php endif; ?>
                            </div>

                            <!-- Expense Details -->
                            <div class="info-card">
                                <h3 class="card-title">Expense Information</h3>
                                
                                <div class="info-row">
                                    <span class="info-label">Expense Number:</span>
                                    <span class="info-value">#<?php echo htmlspecialchars($expense['expense_number']); ?></span>
                                </div>
                                
                                <div class="info-row">
                                    <span class="info-label">Category:</span>
                                    <div>
                                        <span class="info-value"><?php echo htmlspecialchars($expense['category_name']); ?></span>
                                        <?php 
                                        $type_class = match($expense['category_type']) {
                                            'SHOP' => 'type-shop',
                                            'COMPANY' => 'type-company',
                                            'FAMILY' => 'type-family',
                                            default => 'type-shop'
                                        };
                                        ?>
                                        <span class="type-badge <?php echo $type_class; ?> ms-2">
                                            <?php echo ucfirst(str_replace('_', ' ', strtolower($expense['category_type']))); ?>
                                        </span>
                                    </div>
                                </div>
                                
                                <div class="info-row">
                                    <span class="info-label">Expense Date:</span>
                                    <span class="info-value"><?php echo date('F j, Y', strtotime($expense['expense_date'])); ?></span>
                                </div>
                                
                                <div class="info-row">
                                    <span class="info-label">Payment Method:</span>
                                    <div>
                                        <?php 
                                        $payment_class = match($expense['payment_method']) {
                                            'CASH' => 'payment-cash',
                                            'CARD' => 'payment-card',
                                            'BANK_TRANSFER' => 'payment-bank-transfer',
                                            'MPESA' => 'payment-mpesa',
                                            'MOBILE_MONEY' => 'payment-mobile-money',
                                            'CHEQUE' => 'payment-cheque',
                                            default => 'payment-cash'
                                        };
                                        ?>
                                        <span class="payment-badge <?php echo $payment_class; ?>">
                                            <?php echo ucfirst(str_replace('_', ' ', strtolower($expense['payment_method']))); ?>
                                        </span>
                                    </div>
                                </div>
                                
                                <?php if ($expense['payment_reference']): ?>
                                <div class="info-row">
                                    <span class="info-label">Payment Reference:</span>
                                    <span class="info-value"><?php echo htmlspecialchars($expense['payment_reference']); ?></span>
                                </div>
                                <?php endif; ?>
                                
                                <?php if ($expense['vendor_name']): ?>
                                <div class="info-row">
                                    <span class="info-label">Vendor:</span>
                                    <span class="info-value"><?php echo htmlspecialchars($expense['vendor_name']); ?></span>
                                </div>
                                <?php endif; ?>
                                
                                <?php if ($expense['vendor_contact']): ?>
                                <div class="info-row">
                                    <span class="info-label">Vendor Contact:</span>
                                    <span class="info-value"><?php echo htmlspecialchars($expense['vendor_contact']); ?></span>
                                </div>
                                <?php endif; ?>
                                
                                <?php if ($expense['receipt_number']): ?>
                                <div class="info-row">
                                    <span class="info-label">Receipt Number:</span>
                                    <span class="info-value"><?php echo htmlspecialchars($expense['receipt_number']); ?></span>
                                </div>
                                <?php endif; ?>
                                
                                <?php if ($expense['location']): ?>
                                <div class="info-row">
                                    <span class="info-label">Location:</span>
                                    <span class="info-value"><?php echo htmlspecialchars($expense['location']); ?></span>
                                </div>
                                <?php endif; ?>
                                
                                <?php if ($expense['fund_name']): ?>
                                <div class="info-row">
                                    <span class="info-label">Fund Source:</span>
                                    <span class="info-value"><?php echo htmlspecialchars($expense['fund_name']); ?></span>
                                </div>
                                <?php endif; ?>
                                
                                <?php if ($expense['tags']): ?>
                                <div class="info-row">
                                    <span class="info-label">Tags:</span>
                                    <div>
                                        <?php 
                                        $tags = explode(',', $expense['tags']);
                                        foreach ($tags as $tag): 
                                            $tag = trim($tag);
                                            if (!empty($tag)):
                                        ?>
                                            <span style="background: #e0e7ff; color: #3730a3; padding: 0.25rem 0.5rem; border-radius: 4px; font-size: 0.75rem; margin-right: 0.5rem;">
                                                <?php echo htmlspecialchars($tag); ?>
                                            </span>
                                        <?php 
                                            endif;
                                        endforeach; 
                                        ?>
                                    </div>
                                </div>
                                <?php endif; ?>
                            </div>

                            <!-- Recurring Information -->
                            <?php if ($expense['is_recurring']): ?>
                            <div class="info-card">
                                <h3 class="card-title">Recurring Expense Information</h3>
                                
                                <div class="info-row">
                                    <span class="info-label">Frequency:</span>
                                    <span class="info-value"><?php echo ucfirst(str_replace('_', ' ', strtolower($expense['recurring_frequency']))); ?></span>
                                </div>
                                
                                <?php if ($expense['next_due_date']): ?>
                                <div class="info-row">
                                    <span class="info-label">Next Due Date:</span>
                                    <span class="info-value"><?php echo date('F j, Y', strtotime($expense['next_due_date'])); ?></span>
                                </div>
                                <?php endif; ?>
                            </div>
                            <?php endif; ?>

                            <!-- Additional Notes -->
                            <?php if ($expense['notes']): ?>
                            <div class="info-card">
                                <h3 class="card-title">Additional Notes</h3>
                                <p style="color: #374151; line-height: 1.6; margin: 0;">
                                    <?php echo nl2br(htmlspecialchars($expense['notes'])); ?>
                                </p>
                            </div>
                            <?php endif; ?>

                            <!-- Attachments -->
                            <?php if ($attachments->num_rows > 0): ?>
                            <div class="info-card">
                                <h3 class="card-title">Attachments</h3>
                                
                                <?php while ($attachment = $attachments->fetch_assoc()): ?>
                                    <div class="attachment">
                                        <div class="attachment-icon">
                                            <i class="ph-file"></i>
                                        </div>
                                        <div class="attachment-info">
                                            <div class="attachment-name">
                                                <a href="download_attachment.php?id=<?php echo $attachment['attachment_id']; ?>" 
                                                   style="color: #3b82f6; text-decoration: none;">
                                                    <?php echo htmlspecialchars($attachment['original_filename']); ?>
                                                </a>
                                            </div>
                                            <div class="attachment-meta">
                                                <?php echo number_format($attachment['file_size'] / 1024, 1); ?> KB • 
                                                Uploaded: <?php echo date('M j, Y g:i A', strtotime($attachment['uploaded_at'])); ?>
                                            </div>
                                        </div>
                                        <?php if ($role_name === 'Administrator'): ?>
                                        <button class="btn btn-danger btn-sm" onclick="deleteAttachment(<?php echo $attachment['attachment_id']; ?>)">
                                            <i class="ph-trash"></i>
                                        </button>
                                        <?php endif; ?>
                                    </div>
                                <?php endwhile; ?>
                            </div>
                            <?php endif; ?>

                            <!-- Comments Section -->
                            <div class="info-card">
                                <h3 class="card-title">Comments & Notes</h3>
                                
                                <!-- Existing Comments -->
                                <?php if ($comments->num_rows > 0): ?>
                                    <?php while ($comment = $comments->fetch_assoc()): ?>
                                        <div class="comment">
                                            <div class="comment-header">
                                                <span class="comment-author"><?php echo htmlspecialchars($comment['user_name']); ?></span>
                                                <span class="comment-date"><?php echo date('M j, Y g:i A', strtotime($comment['created_at'])); ?></span>
                                            </div>
                                            <div class="comment-text">
                                                <?php echo nl2br(htmlspecialchars($comment['comment_text'])); ?>
                                            </div>
                                            <?php if ($comment['comment_type'] !== 'GENERAL'): ?>
                                                <div style="margin-top: 0.5rem;">
                                                    <small style="background: #f3f4f6; padding: 0.25rem 0.5rem; border-radius: 4px; color: #6b7280;">
                                                        <?php echo ucfirst(strtolower($comment['comment_type'])); ?> Comment
                                                    </small>
                                                </div>
                                            <?php endif; ?>
                                        </div>
                                    <?php endwhile; ?>
                                <?php else: ?>
                                    <p style="color: #64748b; text-align: center; padding: 2rem;">No comments yet.</p>
                                <?php endif; ?>
                                
                                <!-- Add Comment Form -->
                                <form method="POST" style="margin-top: 1.5rem; padding-top: 1.5rem; border-top: 1px solid #e2e8f0;">
                                    <input type="hidden" name="add_comment" value="1">
                                    
                                    <div class="row">
                                        <div class="col-md-8">
                                            <label class="form-label">Add Comment:</label>
                                            <textarea class="form-control" name="comment_text" rows="3" placeholder="Enter your comment..." required></textarea>
                                        </div>
                                        <div class="col-md-4">
                                            <label class="form-label">Comment Type:</label>
                                            <select class="form-select" name="comment_type">
                                                <option value="GENERAL">General</option>
                                                <option value="APPROVAL">Approval</option>
                                                <option value="MODIFICATION">Modification</option>
                                                <option value="SYSTEM">System</option>
                                            </select>
                                            
                                            <?php if ($role_name === 'Administrator'): ?>
                                            <div class="form-check mt-2">
                                                <input class="form-check-input" type="checkbox" name="is_internal" id="isInternal">
                                                <label class="form-check-label" for="isInternal">
                                                    Internal Comment
                                                </label>
                                            </div>
                                            <?php endif; ?>
                                            
                                            <button type="submit" class="btn btn-primary mt-2">
                                                <i class="ph-chat-circle me-1"></i> Add Comment
                                            </button>
                                        </div>
                                    </div>
                                </form>
                            </div>
                        </div>

                        <!-- Sidebar -->
                        <div class="col-lg-4">
                            <!-- Action Buttons -->
                            <div class="info-card">
                                <h3 class="card-title">Actions</h3>
                                
                                <div class="d-grid gap-2">
                                    <?php if (in_array($expense['status'], ['DRAFT', 'PENDING'])): ?>
                                        <a href="edit_expense.php?id=<?php echo $expense['expense_id']; ?>" class="btn btn-warning">
                                            <i class="ph-pencil"></i> Edit Expense
                                        </a>
                                    <?php endif; ?>
                                    
                                    <?php if ($expense['status'] === 'PENDING' && in_array($role_name, ['Administrator', 'Fund Manager'])): ?>
                                        <button type="button" class="btn btn-success" onclick="approveExpense()">
                                            <i class="ph-check"></i> Approve Expense
                                        </button>
                                        
                                        <button type="button" class="btn btn-danger" onclick="rejectExpense()">
                                            <i class="ph-x"></i> Reject Expense
                                        </button>
                                    <?php endif; ?>
                                    
                                    <?php if ($expense['status'] === 'APPROVED' && in_array($role_name, ['Administrator', 'Fund Manager'])): ?>
                                        <button type="button" class="btn btn-success" onclick="markAsPaid()">
                                            <i class="ph-check-circle"></i> Mark as Paid
                                        </button>
                                    <?php endif; ?>
                                    
                                    <a href="print_expense.php?id=<?php echo $expense['expense_id']; ?>" class="btn btn-secondary" target="_blank">
                                        <i class="ph-printer"></i> Print Receipt
                                    </a>
                                    
                                    <?php if (in_array($expense['status'], ['DRAFT', 'REJECTED']) && $role_name === 'Administrator'): ?>
                                        <button type="button" class="btn btn-danger" onclick="deleteExpense()">
                                            <i class="ph-trash"></i> Delete Expense
                                        </button>
                                    <?php endif; ?>
                                    
                                    <a href="list_expenses.php" class="btn btn-secondary">
                                        <i class="ph-arrow-left"></i> Back to List
                                    </a>
                                </div>
                            </div>

                            <!-- Quick Stats -->
                            <div class="info-card">
                                <h3 class="card-title">Quick Information</h3>
                                
                                <div class="info-row">
                                    <span class="info-label">Created By:</span>
                                    <span class="info-value"><?php echo htmlspecialchars($expense['created_by_name']); ?></span>
                                </div>
                                
                                <div class="info-row">
                                    <span class="info-label">Created On:</span>
                                    <span class="info-value"><?php echo date('M j, Y g:i A', strtotime($expense['created_at'])); ?></span>
                                </div>
                                
                                <?php if ($expense['approved_by_name']): ?>
                                <div class="info-row">
                                    <span class="info-label">Approved By:</span>
                                    <span class="info-value"><?php echo htmlspecialchars($expense['approved_by_name']); ?></span>
                                </div>
                                <?php endif; ?>
                                
                                <?php if ($expense['approved_at']): ?>
                                <div class="info-row">
                                    <span class="info-label">Approved On:</span>
                                    <span class="info-value"><?php echo date('M j, Y g:i A', strtotime($expense['approved_at'])); ?></span>
                                </div>
                                <?php endif; ?>
                                
                                <?php if ($expense['paid_by_name']): ?>
                                <div class="info-row">
                                    <span class="info-label">Paid By:</span>
                                    <span class="info-value"><?php echo htmlspecialchars($expense['paid_by_name']); ?></span>
                                </div>
                                <?php endif; ?>
                                
                                <?php if ($expense['paid_at']): ?>
                                <div class="info-row">
                                    <span class="info-label">Paid On:</span>
                                    <span class="info-value"><?php echo date('M j, Y g:i A', strtotime($expense['paid_at'])); ?></span>
                                </div>
                                <?php endif; ?>
                            </div>

                            <!-- Approval History -->
                            <?php if ($approvals->num_rows > 0): ?>
                            <div class="info-card">
                                <h3 class="card-title">Approval History</h3>
                                
                                <div class="timeline">
                                    <?php while ($approval = $approvals->fetch_assoc()): ?>
                                        <div class="timeline-item">
                                            <div class="timeline-content">
                                                <div class="timeline-date">
                                                    <?php echo date('M j, Y g:i A', strtotime($approval['requested_at'])); ?>
                                                </div>
                                                <div class="timeline-title">
                                                    <?php echo ucfirst(strtolower($approval['status'])); ?>
                                                </div>
                                                <div class="timeline-description">
                                                    Requested by: <?php echo htmlspecialchars($approval['requested_by_name']); ?>
                                                    <?php if ($approval['reviewed_by_name']): ?>
                                                        <br>Reviewed by: <?php echo htmlspecialchars($approval['reviewed_by_name']); ?>
                                                    <?php endif; ?>
                                                    <?php if ($approval['comments']): ?>
                                                        <br><em><?php echo htmlspecialchars($approval['comments']); ?></em>
                                                    <?php endif; ?>
                                                </div>
                                            </div>
                                        </div>
                                    <?php endwhile; ?>
                                </div>
                            </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11.7.32/dist/sweetalert2.all.min.js"></script>
    
    <script>
        function approveExpense() {
            Swal.fire({
                title: 'Approve Expense?',
                text: 'Are you sure you want to approve this expense?',
                icon: 'question',
                showCancelButton: true,
                confirmButtonColor: '#059669',
                cancelButtonColor: '#6b7280',
                confirmButtonText: 'Yes, Approve',
                cancelButtonText: 'Cancel'
            }).then((result) => {
                if (result.isConfirmed) {
                    performAction('approve_expense');
                }
            });
        }

        function rejectExpense() {
            Swal.fire({
                title: 'Reject Expense',
                input: 'textarea',
                inputLabel: 'Reason for rejection',
                inputPlaceholder: 'Please provide a reason for rejecting this expense...',
                inputValidator: (value) => {
                    if (!value) {
                        return 'You must provide a reason for rejection!';
                    }
                },
                showCancelButton: true,
                confirmButtonColor: '#dc2626',
                cancelButtonColor: '#6b7280',
                confirmButtonText: 'Reject Expense',
                cancelButtonText: 'Cancel'
            }).then((result) => {
                if (result.isConfirmed) {
                    performAction('reject_expense', { reason: result.value });
                }
            });
        }

        function markAsPaid() {
            Swal.fire({
                title: 'Mark as Paid?',
                text: 'Are you sure this expense has been paid?',
                icon: 'question',
                showCancelButton: true,
                confirmButtonColor: '#059669',
                cancelButtonColor: '#6b7280',
                confirmButtonText: 'Yes, Mark as Paid',
                cancelButtonText: 'Cancel'
            }).then((result) => {
                if (result.isConfirmed) {
                    performAction('mark_paid');
                }
            });
        }

        function deleteExpense() {
            Swal.fire({
                title: 'Delete Expense?',
                text: 'This action cannot be undone. Are you sure you want to delete this expense?',
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#dc2626',
                cancelButtonColor: '#6b7280',
                confirmButtonText: 'Yes, Delete',
                cancelButtonText: 'Cancel'
            }).then((result) => {
                if (result.isConfirmed) {
                    performAction('delete_expense');
                }
            });
        }

        function deleteAttachment(attachmentId) {
            Swal.fire({
                title: 'Delete Attachment?',
                text: 'Are you sure you want to delete this attachment?',
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#dc2626',
                cancelButtonColor: '#6b7280',
                confirmButtonText: 'Yes, Delete',
                cancelButtonText: 'Cancel'
            }).then((result) => {
                if (result.isConfirmed) {
                    // Handle attachment deletion
                    $.post('delete_attachment.php', {
                        attachment_id: attachmentId
                    }, function(response) {
                        if (response.success) {
                            Swal.fire('Deleted!', response.message, 'success').then(() => {
                                location.reload();
                            });
                        } else {
                            Swal.fire('Error!', response.message, 'error');
                        }
                    }, 'json');
                }
            });
        }

        function performAction(action, extraData = {}) {
            const data = {
                action: action,
                ...extraData
            };

            $.post(window.location.href, data, function(response) {
                if (response.success) {
                    Swal.fire('Success!', response.message, 'success').then(() => {
                        if (response.redirect) {
                            window.location.href = response.redirect;
                        } else {
                            location.reload();
                        }
                    });
                } else {
                    Swal.fire('Error!', response.message, 'error');
                }
            }, 'json').fail(function() {
                Swal.fire('Error!', 'An unexpected error occurred. Please try again.', 'error');
            });
        }
    </script>

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

<?php $conn->close(); ?>