<?php
session_start();
if (!isset($_SESSION['user_id'])) {
    header("Location: index");
    exit;
}

// Include database connection
include 'db.php';

// Verify role-based access
checkAccess();

// Verify project access if project_id is provided
if (isset($_GET['project_id']) && !empty($_GET['project_id'])) {
    verifyProjectAccess($_GET['project_id'], $conn);
}
// Also verify for POST requests that contain a project_id
if (isset($_POST['project_id']) && !empty($_POST['project_id'])) {
    verifyProjectAccess($_POST['project_id'], $conn);
}

// Initialize variables
$selectedProject = null;
$expenses = [];
$expenseCount = 0;
$alertMessage = '';
$alertType = '';

// Initialize variables for project-wide totals (always calculated)
$totalProjectExpense = 0;
$totalProjectMaterialsExpense = 0;
$totalProjectLaborExpense = 0;

// Initialize variables for vendor-specific totals (only calculated if order_id is present)
$vendorTotalExpenses = 0;
$vendorPaidAmount = 0;
$vendorRemainingAmount = 0;
$isVendorSpecificView = false; // Flag to indicate if we are in a vendor-specific view
$targetVendorName = ''; // Store target vendor name if in vendor-specific view

// Handle Smart Payment Allocation for Placed Orders (Additive Logic)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'process_order_payment') {
    $projectId = intval($_POST['project_id']);
    $orderId = intval($_POST['order_id']);
    $paymentAmount = floatval($_POST['unit_cost']) * floatval($_POST['quantity']);
    $entryDate = mysqli_real_escape_string($conn, $_POST['entry_date']);

    if ($projectId > 0 && $orderId > 0 && $paymentAmount > 0) {
        mysqli_begin_transaction($conn);
        try {
            // 1. Identify category of the target order first
            $catQuery = "SELECT category FROM placed_orders WHERE id = ? AND project_id = ?";
            $stmt = mysqli_prepare($conn, $catQuery);
            mysqli_stmt_bind_param($stmt, 'ii', $orderId, $projectId);
            mysqli_stmt_execute($stmt);
            $orderInfo = mysqli_fetch_assoc(mysqli_stmt_get_result($stmt));
            mysqli_stmt_close($stmt);
            
            if (!$orderInfo) throw new Exception("Order not found.");
            $category = $orderInfo['category'];

            // 2. Mandatory Payment Validation: Check total category balance (MANDATORY)
            $balQuery = "SELECT SUM(total_amount - paid_amount) as remaining_balance FROM placed_orders WHERE project_id = ? AND category = ? FOR UPDATE";
            $stmt = mysqli_prepare($conn, $balQuery);
            mysqli_stmt_bind_param($stmt, 'is', $projectId, $category);
            mysqli_stmt_execute($stmt);
            $balRes = mysqli_stmt_get_result($stmt);
            $balanceData = mysqli_fetch_assoc($balRes);
            $remainingCategoryAmount = floatval($balanceData['remaining_balance'] ?? 0);
            mysqli_stmt_close($stmt);

            // 3. Mandatory Check: Is the category already fully paid?
            if ($remainingCategoryAmount <= 0) {
                throw new Exception("This category is already fully paid across all orders.");
            }

            if ($paymentAmount > ($remainingCategoryAmount + 0.01)) { // Added small epsilon for float precision
                throw new Exception("Overpayment Error: Remaining category balance is ₹" . number_format($remainingCategoryAmount, 2) . ". You attempted to pay ₹" . number_format($paymentAmount, 2));
            }

            // 4. Get the specific target order for allocation
            $q = "SELECT id, total_amount, paid_amount FROM placed_orders WHERE id = ? AND project_id = ? FOR UPDATE";
            $stmt = mysqli_prepare($conn, $q);
            mysqli_stmt_bind_param($stmt, 'ii', $orderId, $projectId);
            mysqli_stmt_execute($stmt);
            $targetOrder = mysqli_fetch_assoc(mysqli_stmt_get_result($stmt));
            mysqli_stmt_close($stmt);

            if (!$targetOrder) throw new Exception("Target order not found.");

            // 5. Strict Validation: Prevent paying a completed order directly
            if ($targetOrder['paid_amount'] >= $targetOrder['total_amount']) {
                throw new Exception("Transaction Aborted: Order #$orderId is already fully paid. Please select a pending order.");
            }

            $remainingToAllocate = $paymentAmount;

            // 6. Process Target Order Allocation
            $currentPaid = floatval($targetOrder['paid_amount']);
            $totalAmount = floatval($targetOrder['total_amount']);
            $needed = max(0, $totalAmount - $currentPaid);
            $toAdd = min($remainingToAllocate, $needed);

            if ($toAdd > 0) {
                $newPaid = $currentPaid + $toAdd;
                $newRemaining = max(0, $totalAmount - $newPaid);

                // DEBUG LOG
                error_log("[Allocation Target #$orderId] Current: $currentPaid, Needed: $needed, Adding: $toAdd, NewPaid: $newPaid, NewRem: $newRemaining");

                $upd = "UPDATE placed_orders SET paid_amount = ?, remaining_amount = ?, payment_date = ? WHERE id = ?";
                $stmt = mysqli_prepare($conn, $upd);
                mysqli_stmt_bind_param($stmt, 'ddsi', $newPaid, $newRemaining, $entryDate, $orderId);
                mysqli_stmt_execute($stmt);
                mysqli_stmt_close($stmt);
                
                $remainingToAllocate -= $toAdd;
            }

            // 7. Smart Allocation: Only if money remains
            if ($remainingToAllocate > 0.005) {
                $q2 = "SELECT id, total_amount, paid_amount FROM placed_orders 
                       WHERE project_id = ? AND category = ? AND id != ? AND paid_amount < total_amount 
                       ORDER BY order_date ASC, id ASC FOR UPDATE";
                $stmt = mysqli_prepare($conn, $q2);
                mysqli_stmt_bind_param($stmt, 'isi', $projectId, $category, $orderId);
                mysqli_stmt_execute($stmt);
                $res2 = mysqli_stmt_get_result($stmt);
                
                while ($row = mysqli_fetch_assoc($res2)) {
                    if ($remainingToAllocate <= 0.005) break;
                    
                    $rowId = $row['id'];
                    $rowPaid = floatval($row['paid_amount']);
                    $rowTotal = floatval($row['total_amount']);
                    
                    $neededOther = max(0, $rowTotal - $rowPaid);
                    $toAddOther = min($remainingToAllocate, $neededOther);
                    
                    if ($toAddOther > 0) {
                        $newPaidOther = $rowPaid + $toAddOther;
                        $newRemOther = max(0, $rowTotal - $newPaidOther);

                        // DEBUG LOG
                        error_log("[Allocation Smart #$rowId] Current: $rowPaid, Needed: $neededOther, Adding: $toAddOther, NewPaid: $newPaidOther, NewRem: $newRemOther");

                        $stmt2 = mysqli_prepare($conn, "UPDATE placed_orders SET paid_amount = ?, remaining_amount = ?, payment_date = ? WHERE id = ?");
                        mysqli_stmt_bind_param($stmt2, 'ddsi', $newPaidOther, $newRemOther, $entryDate, $rowId);
                        mysqli_stmt_execute($stmt2);
                        mysqli_stmt_close($stmt2);
                        
                        $remainingToAllocate -= $toAddOther;
                    }
                }
                mysqli_stmt_close($stmt);
            }

            mysqli_commit($conn);
            header("Location: place_order?project_id=" . $projectId . "&payment_success=1");
            exit;
        } catch (Exception $e) {
            mysqli_rollback($conn);
            $alertMessage = $e->getMessage();
            $alertType = 'danger';
        }
    }
}

// Handle expense addition (POST)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'add_expense') {
    $projectId = intval($_POST['project_id']);
    $category = mysqli_real_escape_string($conn, $_POST['category']);
    $unitCost = floatval($_POST['unit_cost']);
    $quantity = floatval($_POST['quantity']);
    $amount = $unitCost * $quantity; // Calculate total cost automatically
    $entryDate = mysqli_real_escape_string($conn, $_POST['entry_date']);
    $recordedBy = mysqli_real_escape_string($conn, $_POST['recorded_by']);
    $description = mysqli_real_escape_string($conn, $_POST['description'] ?? $category . ' expense');

    // Validation
    if ($projectId <= 0) {
        $alertMessage = 'Please select a valid project.';
        $alertType = 'danger';
    } elseif ($unitCost <= 0) {
        $alertMessage = 'Unit cost must be greater than 0.';
        $alertType = 'danger';
    } elseif ($quantity <= 0) {
        $alertMessage = 'Quantity must be greater than 0.';
        $alertType = 'danger';
    } elseif (empty($category) || empty($entryDate) || empty($recordedBy)) {
        $alertMessage = 'All fields are required.';
        $alertType = 'danger';
    } else {
        // Insert expense with unit_cost, quantity, and recorded_by
        $insertQuery = "INSERT INTO finance_entries (project_id, entry_type, category, description, amount, unit_cost, quantity, recorded_by, entry_date, created_by_user_id) VALUES (?, 'Expense', ?, ?, ?, ?, ?, ?, ?, ?)";
        $stmt = mysqli_prepare($conn, $insertQuery);
        mysqli_stmt_bind_param($stmt, 'isssddssi', $projectId, $category, $description, $amount, $unitCost, $quantity, $recordedBy, $entryDate, $_SESSION['user_id']);
        if (mysqli_stmt_execute($stmt)) {
            $alertMessage = 'Expense added successfully!';
            $alertType = 'success';
            // Redirect to reload the page with current project
            header("Location: financetracker/" . $projectId);
            exit;
        } else {
            $alertMessage = 'Error adding expense: ' . mysqli_error($conn);
            $alertType = 'danger';
        }
        mysqli_stmt_close($stmt);
    }
}

// Handle expense editing (POST) - Returns JSON for AJAX requests
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'edit_expense') {
    $expenseId = intval($_POST['expense_id']);
    $projectId = intval($_POST['project_id']);
    $category = mysqli_real_escape_string($conn, $_POST['category']);
    $unitCost = floatval($_POST['unit_cost']);
    $quantity = floatval($_POST['quantity']);
    $amount = floatval($_POST['amount']);
    $entryDate = mysqli_real_escape_string($conn, $_POST['entry_date']);
    $recordedBy = mysqli_real_escape_string($conn, $_POST['recorded_by']);
    $description = mysqli_real_escape_string($conn, $_POST['description'] ?? $category . ' expense');

    header('Content-Type: application/json');
    
    // Validation
    if ($projectId <= 0 || $expenseId <= 0) {
        echo json_encode(['success' => false, 'message' => 'Invalid project or expense.']);
        exit;
    } elseif ($amount <= 0) {
        echo json_encode(['success' => false, 'message' => 'Amount must be greater than 0.']);
        exit;
    } elseif (empty($category) || empty($entryDate) || empty($recordedBy)) {
        echo json_encode(['success' => false, 'message' => 'All fields are required.']);
        exit;
    } else {
        // Verify expense belongs to current project
        $checkQuery = "SELECT id FROM finance_entries WHERE id = ? AND project_id = ? AND entry_type = 'Expense'";
        $stmt = mysqli_prepare($conn, $checkQuery);
        mysqli_stmt_bind_param($stmt, 'ii', $expenseId, $projectId);
        mysqli_stmt_execute($stmt);
        $checkResult = mysqli_stmt_get_result($stmt);
        if ($checkResult->num_rows > 0) {
            // Update expense - now includes unit_cost, quantity, recorded_by
            $updateQuery = "UPDATE finance_entries SET category = ?, description = ?, amount = ?, unit_cost = ?, quantity = ?, recorded_by = ?, entry_date = ? WHERE id = ? AND project_id = ?";
            $stmt = mysqli_prepare($conn, $updateQuery);
            mysqli_stmt_bind_param($stmt, 'sssddssii', $category, $description, $amount, $unitCost, $quantity, $recordedBy, $entryDate, $expenseId, $projectId);
            if (mysqli_stmt_execute($stmt)) {
                echo json_encode(['success' => true, 'message' => 'Expense updated successfully!']);
                exit;
            } else {
                echo json_encode(['success' => false, 'message' => 'Error updating expense: ' . mysqli_error($conn)]);
                exit;
            }
        } else {
            echo json_encode(['success' => false, 'message' => 'Expense not found or access denied.']);
            exit;
        }
        mysqli_stmt_close($stmt);
    }
}

// Handle AJAX request to get expense data for editing
if ($_SERVER['REQUEST_METHOD'] === 'GET' && isset($_GET['action']) && $_GET['action'] === 'get_expense') {
    $expenseId = intval($_GET['expense_id']);
    $projectId = intval($_GET['project_id']);
    
    header('Content-Type: application/json');
    
    if ($expenseId > 0 && $projectId > 0) {
        $fetchExpenseQuery = "SELECT id, category, description, amount, unit_cost, quantity, recorded_by, entry_date FROM finance_entries WHERE id = ? AND project_id = ? AND entry_type = 'Expense'";
        $stmt = mysqli_prepare($conn, $fetchExpenseQuery);
        mysqli_stmt_bind_param($stmt, 'ii', $expenseId, $projectId);
        mysqli_stmt_execute($stmt);
        $fetchResult = mysqli_stmt_get_result($stmt);
        if ($fetchResult && mysqli_num_rows($fetchResult) > 0) {
            $expenseData = mysqli_fetch_assoc($fetchResult);
            echo json_encode(['success' => true, 'data' => $expenseData]);
        } else {
            echo json_encode(['success' => false, 'message' => 'Expense not found']);
        }
        mysqli_stmt_close($stmt);
    } else {
        echo json_encode(['success' => false, 'message' => 'Invalid parameters']);
    }
    exit;
}

// Initialize edit expense data for modal
$editExpenseData = null;
if (isset($_GET['edit_expense']) && isset($_GET['project_id'])) {
    $editExpenseId = intval($_GET['edit_expense']);
    $editProjectId = intval($_GET['project_id']);
    
    if ($editExpenseId > 0 && $editProjectId > 0) {
        $fetchExpenseQuery = "SELECT id, category, description, amount, unit_cost, quantity, recorded_by, entry_date FROM finance_entries WHERE id = ? AND project_id = ? AND entry_type = 'Expense'";
        $stmt = mysqli_prepare($conn, $fetchExpenseQuery);
        mysqli_stmt_bind_param($stmt, 'ii', $editExpenseId, $editProjectId);
        mysqli_stmt_execute($stmt);
        $fetchResult = mysqli_stmt_get_result($stmt);
        if ($fetchResult && mysqli_num_rows($fetchResult) > 0) {
            $editExpenseData = mysqli_fetch_assoc($fetchResult);
        }
        mysqli_stmt_close($stmt);
    }
}

// Handle expense deletion (POST)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'delete_expense') {
    $expenseId = intval($_POST['expense_id']);
    $projectId = intval($_POST['project_id']);

    if ($projectId <= 0 || $expenseId <= 0) {
        $alertMessage = 'Invalid project or expense.';
        $alertType = 'danger';
    } else {
        // Verify expense belongs to current project and user
        $checkQuery = "SELECT id FROM finance_entries WHERE id = ? AND project_id = ? AND entry_type = 'Expense'";
        $stmt = mysqli_prepare($conn, $checkQuery);
        mysqli_stmt_bind_param($stmt, 'ii', $expenseId, $projectId);
        mysqli_stmt_execute($stmt);
        $checkResult = mysqli_stmt_get_result($stmt);
        if ($checkResult->num_rows > 0) {
            // Delete expense
            $deleteQuery = "DELETE FROM finance_entries WHERE id = ? AND project_id = ?";
            $stmt = mysqli_prepare($conn, $deleteQuery);
            mysqli_stmt_bind_param($stmt, 'ii', $expenseId, $projectId);
            if (mysqli_stmt_execute($stmt)) {
                $alertMessage = 'Expense deleted successfully!';
                $alertType = 'success';
                // Redirect to reload the page
                header("Location: financetracker/" . $projectId);
                exit;
            } else {
                $alertMessage = 'Error deleting expense: ' . mysqli_error($conn);
                $alertType = 'danger';
            }
        } else {
            $alertMessage = 'Expense not found or access denied.';
            $alertType = 'danger';
        }
        mysqli_stmt_close($stmt);
    }
}

// Handle project selection (GET)
if (isset($_GET['project_id'])) {
    $projectId = intval($_GET['project_id']);
    if ($projectId > 0) {
        // Fetch project details
        $projectQuery = "SELECT p.id, p.project_name, c.client_name FROM projects p JOIN clients c ON p.client_id = c.id WHERE p.id = ?";
        $stmt = mysqli_prepare($conn, $projectQuery);
        mysqli_stmt_bind_param($stmt, 'i', $projectId);
        mysqli_stmt_execute($stmt);
        $projectResult = mysqli_stmt_get_result($stmt);
        if ($projectResult && $projectResult->num_rows > 0) {
            $selectedProject = mysqli_fetch_assoc($projectResult);
            $selectedProject['project_id_display'] = 'PRJ-' . str_pad($selectedProject['id'], 3, '0', STR_PAD_LEFT);
        }
        mysqli_stmt_close($stmt);

        // Dual Mode Data Loading Logic (Context-Aware)
        if (isset($_GET['order_id']) || isset($_GET['place_order_id'])) {
            // Mode 2: Order Redirect - Load related item transactions from placed_orders table
            $orderId = intval($_GET['place_order_id'] ?? $_GET['order_id']);
            
            // First, determine the item type and vendor of the selected order
            $ctxQuery = "SELECT item, vendor_name FROM placed_orders WHERE id = ? AND project_id = ?";
            $ctxStmt = mysqli_prepare($conn, $ctxQuery);
            mysqli_stmt_bind_param($ctxStmt, 'ii', $orderId, $projectId);
            mysqli_stmt_execute($ctxStmt);
            $orderContext = mysqli_fetch_assoc(mysqli_stmt_get_result($ctxStmt));
            mysqli_stmt_close($ctxStmt);

            if ($orderContext) {
                $targetItem = $orderContext['item'];
                $targetVendor = $orderContext['vendor_name'];

                // Calculate vendor specific stats for summary cards (Dynamic Calculation)
                $aggQuery = "SELECT 
                    SUM(total_amount) as total_exp,
                    SUM(paid_amount) as total_paid,
                    SUM(remaining_amount) as total_rem
                    FROM placed_orders 
                    WHERE project_id = ? AND vendor_name <=> ?";
                
                $aggStmt = mysqli_prepare($conn, $aggQuery);
                mysqli_stmt_bind_param($aggStmt, 'is', $projectId, $targetVendor);
                mysqli_stmt_execute($aggStmt);
                $aggRes = mysqli_fetch_assoc(mysqli_stmt_get_result($aggStmt));
                mysqli_stmt_close($aggStmt);

                $vendorTotalExpenses = floatval($aggRes['total_exp'] ?? 0);
                $vendorPaidAmount = floatval($aggRes['total_paid'] ?? 0);
                $vendorRemainingAmount = floatval($aggRes['total_rem'] ?? 0);
                $isVendorSpecificView = true;

                // Recent Transactions logic:
                // 1) Filter by vendor from the passed order_id
                // 2) If item exists, prioritize same item within that vendor
                // 3) Order latest first
                $targetVendor = $orderContext['vendor_name'] ?? '';
                $targetItemForOrder = $orderContext['item'] ?? '';

                if (!empty($targetVendor)) {
                    if (!empty($targetItemForOrder)) {
                        $expenseQuery = "SELECT 
                            id,
                            item,
                            category,
                            details,
                            CONCAT(COALESCE(vendor_name, 'Labour Work'), ' - ', item) as description,
                            total_amount AS amount,
                            paid_amount,
                            remaining_amount,
                            total_amount as unit_cost,
                            1.00 as quantity,
                            recorded_by,
                            order_date AS entry_date,
                            created_at
                        FROM placed_orders
                        WHERE project_id = ? AND vendor_name <=> ? AND item <=> ?
                        ORDER BY order_date DESC, created_at DESC";
                        $stmt = mysqli_prepare($conn, $expenseQuery);
                        mysqli_stmt_bind_param($stmt, 'iss', $projectId, $targetVendor, $targetItemForOrder);
                    } else {
                        $expenseQuery = "SELECT 
                            id,
                            item,
                            category,
                            details,
                            CONCAT(COALESCE(vendor_name, 'Labour Work'), ' - ', item) as description,
                            total_amount AS amount,
                            paid_amount,
                            remaining_amount,
                            total_amount as unit_cost,
                            1.00 as quantity,
                            recorded_by,
                            order_date AS entry_date,
                            created_at
                        FROM placed_orders
                        WHERE project_id = ? AND vendor_name <=> ?
                        ORDER BY order_date DESC, created_at DESC";
                        $stmt = mysqli_prepare($conn, $expenseQuery);
                        mysqli_stmt_bind_param($stmt, 'is', $projectId, $targetVendor);
                    }
                } else {
                    // Fallback: keep existing "invalid order_id => nothing" behavior
                    $expenseQuery = "SELECT id FROM finance_entries WHERE 1=0";
                    $stmt = mysqli_prepare($conn, $expenseQuery);
                }
            } else {
                // If invalid order_id, ignore default tracker listing and show nothing
                $expenseQuery = "SELECT id FROM finance_entries WHERE 1=0";
                $stmt = mysqli_prepare($conn, $expenseQuery);
            }
        } else {
            // Mode 1: Normal Open (No Order ID) - Behave exactly as it currently works
            $expenseQuery = "SELECT id, category, description, amount, unit_cost, quantity, recorded_by, entry_date, created_at, NULL as remaining_amount, NULL as item, NULL as details FROM finance_entries WHERE project_id = ? AND entry_type = 'Expense' ORDER BY entry_date DESC, created_at DESC";
            $stmt = mysqli_prepare($conn, $expenseQuery);
            mysqli_stmt_bind_param($stmt, 'i', $projectId);
        }

        mysqli_stmt_execute($stmt);
        $expenseResult = mysqli_stmt_get_result($stmt);
        if ($expenseResult) {
            while ($row = mysqli_fetch_assoc($expenseResult)) {
                $expenses[] = $row;
                $totalProjectExpense += $row['amount'];
                $expenseCount++;
                if ($row['category'] === 'Materials') {
                    $totalProjectMaterialsExpense += $row['amount'];
                } elseif ($row['category'] === 'Labor') {
                    $totalProjectLaborExpense += $row['amount'];
                }
            }
        }
        mysqli_stmt_close($stmt);
    }
}

// Handle pre-filling for Order Payment (Additive)
$prefilledOrder = null;
$categoryRemainingBalance = 0;
if ((isset($_GET['order_id']) || isset($_GET['place_order_id'])) && isset($_GET['project_id'])) {
    $oid = intval($_GET['place_order_id'] ?? $_GET['order_id']);
    $pid = intval($_GET['project_id']);
    $preStmt = mysqli_prepare($conn, "SELECT id, category, vendor_name, item, total_amount, paid_amount, remaining_amount FROM placed_orders WHERE id = ? AND project_id = ?");
    mysqli_stmt_bind_param($preStmt, 'ii', $oid, $pid);
    mysqli_stmt_execute($preStmt);
    $prefilledOrder = mysqli_fetch_assoc(mysqli_stmt_get_result($preStmt));
    mysqli_stmt_close($preStmt);

    if ($prefilledOrder) {
        $balStmt = mysqli_prepare($conn, "SELECT SUM(total_amount - paid_amount) as bal FROM placed_orders WHERE project_id = ? AND category = ?");
        mysqli_stmt_bind_param($balStmt, 'is', $pid, $prefilledOrder['category']);
        mysqli_stmt_execute($balStmt);
        $balRes = mysqli_fetch_assoc(mysqli_stmt_get_result($balStmt));
        $categoryRemainingBalance = floatval($balRes['bal'] ?? 0);
        mysqli_stmt_close($balStmt);
    }
}
// Get logged-in user name
$user_name = 'Admin User';
if (isset($_SESSION['user_id'])) { // This is already checked at the top, but good for robustness
    $userQuery = "SELECT name FROM users WHERE id = ?";
    $stmt = mysqli_prepare($conn, $userQuery);
    mysqli_stmt_bind_param($stmt, 'i', $_SESSION['user_id']);
    mysqli_stmt_execute($stmt);
    $userResult = mysqli_stmt_get_result($stmt);
    if ($userResult && mysqli_num_rows($userResult) > 0) {
        $user = mysqli_fetch_assoc($userResult);
        $user_name = $user['name'];
    }
    mysqli_stmt_close($stmt);
}

// Query to get projects with client information
$projects = getUserProjects($conn);
$projectOptions = '';
$projectDataJS = '';

foreach ($projects as $project) {
    $projectIdDisplay = 'PRJ-' . str_pad($project['id'], 3, '0', STR_PAD_LEFT);
    $projectOptions .= '<option value="' . $project['id'] . '"' . (isset($_GET['project_id']) && $_GET['project_id'] == $project['id'] ? ' selected' : '') . '>' . htmlspecialchars($project['project_name']) . ' - ' . htmlspecialchars($project['client_name']) . '</option>';
    $projectDataJS .= "'" . $project['id'] . "': { name: '" . addslashes($project['project_name']) . "', client: '" . addslashes($project['client_name']) . "', id: '" . $projectIdDisplay . "' },";
}
if (!empty($projectDataJS)) {
    $projectDataJS = rtrim($projectDataJS, ',');
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Finance Tracker - ConstructCRM</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.css">
    
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">

    <style>
    :root {
        --primary-color: #977C49;
        --primary-dark: #7a633a;
        --primary-light: #f8f5ef;
        --secondary-color: #343a40;
        --secondary-light: #f8f9fa;
        --success-color: #28a745;
        --info-color: #17a2b8;
        --warning-color: #ffc107;
        --danger-color: #dc3545;
        --light-color: #f8f9fa;
        --dark-color: #343a40;
        --sidebar-width: 320px;
        --nav-width: 260px;
        --header-height: 70px;
        --footer-height: 40px;
        --border-radius: 12px;
        --box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
        --transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
    }

    * {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
    }

    body {
        font-family: 'Inter', sans-serif;
        background: linear-gradient(135deg, #f5f7fa 0%, #e9ecef 100%);
        color: #2c3e50;
        font-size: 14px;
        line-height: 1.4;
        overflow-x: hidden;
    }

    /* Header - Same as previous pages */
    .header {
        background-color: #fff;
        box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        height: var(--header-height);
        z-index: 1000;
        display: flex;
        align-items: center;
        padding: 0 20px;
    }

    .logo {
        display: flex;
        align-items: center;
        font-weight: 700;
        font-size: 20px;
        color: var(--primary-color);
        text-decoration: none;
    }

    .logo i {
        font-size: 24px;
        margin-right: 10px;
    }

    .header-actions {
        margin-left: auto;
        display: flex;
        align-items: center;
    }

    .mobile-menu-toggle {
        display: none;
        background: none;
        border: none;
        font-size: 24px;
        color: var(--primary-color);
        margin-right: 15px;
        cursor: pointer;
    }

    /* User Dropdown - Same as previous pages */
    .user-dropdown {
        position: relative;
    }

    .user-profile {
        display: flex;
        align-items: center;
        cursor: pointer;
        padding: 5px 10px;
        border-radius: var(--border-radius);
        transition: var(--transition);
    }

    .user-profile:hover {
        background-color: #f8f9fa;
    }

    .user-avatar {
        width: 36px;
        height: 36px;
        border-radius: 50%;
        background-color: var(--primary-color);
        color: white;
        display: flex;
        align-items: center;
        justify-content: center;
        font-weight: 600;
        margin-right: 10px;
    }

    .user-name {
        font-weight: 500;
        margin-right: 5px;
    }

    .dropdown-arrow {
        font-size: 12px;
        color: #666;
        transition: var(--transition);
    }

    .user-dropdown.show .dropdown-arrow {
        transform: rotate(180deg);
    }

    .user-dropdown-menu {
        position: absolute;
        top: 100%;
        right: 0;
        background-color: #fff;
        border-radius: var(--border-radius);
        box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
        min-width: 180px;
        padding: 8px 0;
        margin-top: 5px;
        opacity: 0;
        visibility: hidden;
        transform: translateY(-10px);
        transition: var(--transition);
        z-index: 1001;
    }

    .user-dropdown.show .user-dropdown-menu {
        opacity: 1;
        visibility: visible;
        transform: translateY(0);
    }

    .dropdown-item {
        display: flex;
        align-items: center;
        padding: 10px 20px;
        color: #555;
        text-decoration: none;
        transition: var(--transition);
    }

    .dropdown-item:hover {
        background-color: #f8f9fa;
        color: var(--primary-color);
    }

    .dropdown-item i {
        margin-right: 10px;
        font-size: 16px;
    }

    .dropdown-divider {
        height: 1px;
        background-color: #eee;
        margin: 8px 0;
    }

    /* Main Layout */
    .main-container {
        display: flex;
        min-height: calc(100vh - var(--header-height));
        margin-top: var(--header-height);
    }

    /* Sidebar Navigation - Same as previous pages */
    .sidebar-nav {
        width: var(--nav-width);
        background-color: #fff;
        box-shadow: 2px 0 10px rgba(0, 0, 0, 0.05);
        position: fixed;
        top: var(--header-height);
        left: 0;
        bottom: 0;
        z-index: 999;
        overflow-y: auto;
        transition: var(--transition);
    }

    .nav-section {
        padding: 15px 0;
    }

    .nav-section:last-child {
        padding-bottom: 20px;
    }

    .nav-title {
        font-size: 11px;
        font-weight: 600;
        text-transform: uppercase;
        letter-spacing: 0.5px;
        color: #999;
        padding: 0 20px;
        margin-bottom: 10px;
    }

    .nav-list {
        list-style: none;
    }

    .nav-item {
        margin-bottom: 5px;
    }

    .nav-link {
        display: flex;
        align-items: center;
        padding: 12px 20px;
        color: #555;
        text-decoration: none;
        font-weight: 500;
        transition: var(--transition);
        position: relative;
    }

    .nav-link i {
        font-size: 18px;
        margin-right: 12px;
        width: 20px;
        text-align: center;
    }

    .nav-link:hover {
        background-color: rgba(151, 124, 73, 0.05);
        color: var(--primary-color);
    }

    .nav-link.active {
        background-color: rgba(151, 124, 73, 0.1);
        color: var(--primary-color);
    }

    .nav-link.active::before {
        content: '';
        position: absolute;
        left: 0;
        top: 0;
        bottom: 0;
        width: 4px;
        background-color: var(--primary-color);
    }

    /* Content Wrapper - Same as previous pages */
    .content-wrapper {
        flex: 1;
        margin-left: var(--nav-width);
        display: flex;
        flex-direction: column;
        transition: var(--transition);
    }

    .content-header {
        background-color: #fff;
        padding: 20px 30px;
        border-bottom: 1px solid #eee;
        display: flex;
        align-items: center;
        justify-content: space-between;
    }

    .page-title {
        font-size: 24px;
        font-weight: 600;
        color: #333;
    }

    .breadcrumb {
        background-color: transparent;
        padding: 0;
        margin: 0;
        font-size: 13px;
    }

    .breadcrumb-item {
        color: #999;
    }

    .breadcrumb-item a {
        color: #999;
        text-decoration: none;
        transition: var(--transition);
    }

    .breadcrumb-item a:hover {
        color: var(--primary-color);
    }

    .breadcrumb-item.active {
        color: var(--primary-color);
    }

    .breadcrumb-item + .breadcrumb-item::before {
        content: "›";
        color: #ccc;
    }

    /* Main Content */
    .main-content {
        flex: 1;
        padding: 30px;
        overflow-y: auto;
    }

    /* Project Info Card */
    .project-info-card {
        background-color: #fff;
        border-radius: var(--border-radius);
        box-shadow: var(--box-shadow);
        margin-bottom: 30px;
        overflow: hidden;
    }

    .project-info-header {
        background-color: var(--primary-color);
        color: white;
        padding: 15px 20px;
        font-weight: 600;
        font-size: 18px;
    }

    .project-info-body {
        padding: 30px;
        display: flex;
        align-items: center;
    }

    .project-name {
        font-size: 16px;
        font-weight: 500;
    }

    .project-id {
        margin-left: auto;
        background-color: var(--primary-light);
        color: var(--primary-color);
        padding: 5px 10px;
        border-radius: 20px;
        font-size: 12px;
        font-weight: 600;
    }

    /* Stats Cards - Enhanced */
    .stats-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
        gap: 25px;
        margin-bottom: 40px;
    }

    .stat-card {
        background: linear-gradient(135deg, #fff 0%, #f8f9fa 100%);
        border-radius: var(--border-radius);
        box-shadow: var(--box-shadow);
        padding: 25px;
        display: flex;
        align-items: center;
        transition: var(--transition);
        position: relative;
        overflow: hidden;
    }

    .stat-card::before {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        height: 4px;
        background: linear-gradient(90deg, var(--primary-color), var(--primary-dark));
    }

    .stat-card:hover {
        transform: translateY(-5px);
        box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
    }

    .stat-icon {
        width: 60px;
        height: 60px;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 20px;
        font-size: 28px;
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    }

    .stat-icon.total {
        background: linear-gradient(135deg, var(--primary-color), var(--primary-dark));
        color: white;
    }

    .stat-icon.materials {
        background: linear-gradient(135deg, var(--info-color), #138496);
        color: white;
    }

    .stat-icon.labor {
        background: linear-gradient(135deg, var(--success-color), #218838);
        color: white;
    }

    .stat-details h3 {
        font-size: 28px;
        font-weight: 700;
        margin: 0;
        color: var(--dark-color);
    }

    .stat-details p {
        font-size: 14px;
        color: #999;
        margin: 5px 0 0 0;
        font-weight: 500;
    }

    /* Content Grid - Enhanced */
    .content-grid {
        display: grid;
        grid-template-columns: 400px 1fr;
        gap: 30px;
        align-items: start;
    }

    /* Form Container - Enhanced */
    .form-container {
        background: linear-gradient(135deg, #fff 0%, #f8f9fa 100%);
        border-radius: var(--border-radius);
        box-shadow: var(--box-shadow);
        overflow: hidden;
        position: sticky;
        top: 100px;
    }

    .form-header {
        background: linear-gradient(135deg, var(--primary-color), var(--primary-dark));
        color: white;
        padding: 25px 30px;
        display: flex;
        align-items: center;
        gap: 12px;
    }

    .form-title {
        font-size: 20px;
        font-weight: 600;
        margin: 0;
    }

    .form-body {
        padding: 30px;
    }

    .form-group {
        margin-bottom: 25px;
    }

    .form-label {
        font-weight: 600;
        color: var(--dark-color);
        margin-bottom: 10px;
        font-size: 14px;
        display: flex;
        align-items: center;
        gap: 8px;
    }

    .form-label i {
        color: var(--primary-color);
        font-size: 16px;
    }

    .form-control, .form-select {
        border: 2px solid #e9ecef;
        border-radius: var(--border-radius);
        padding: 12px 16px;
        font-size: 14px;
        transition: var(--transition);
        background: #fff;
    }

    .form-control:focus, .form-select:focus {
        border-color: var(--primary-color);
        box-shadow: 0 0 0 4px rgba(151, 124, 73, 0.1);
        outline: none;
        transform: translateY(-2px);
    }

    .btn {
        border-radius: var(--border-radius);
        font-weight: 600;
        padding: 12px 24px;
        font-size: 14px;
        transition: var(--transition);
        cursor: pointer;
        border: none;
        display: inline-flex;
        align-items: center;
        gap: 8px;
    }

    .btn-primary {
        background: linear-gradient(135deg, var(--primary-color), var(--primary-dark));
        color: white;
        box-shadow: 0 4px 12px rgba(151, 124, 73, 0.3);
    }

    .btn-primary:hover {
        transform: translateY(-3px);
        box-shadow: 0 8px 20px rgba(151, 124, 73, 0.4);
    }

    .btn-primary:active {
        transform: translateY(-1px);
    }

    /* Expense List Container - Enhanced */
    .expense-list-container {
        background: linear-gradient(135deg, #fff 0%, #f8f9fa 100%);
        border-radius: var(--border-radius);
        box-shadow: var(--box-shadow);
        overflow: hidden;
        display: flex;
        flex-direction: column;
        max-height: 800px;
    }

    .expense-list-header {
        background: linear-gradient(135deg, var(--primary-color), var(--primary-dark));
        color: white;
        padding: 25px 30px;
        display: flex;
        align-items: center;
        justify-content: space-between;
    }

    .expense-list-title {
        font-size: 20px;
        font-weight: 600;
        margin: 0;
        display: flex;
        align-items: center;
        gap: 12px;
    }

    .expense-count {
        background: rgba(255, 255, 255, 0.2);
        padding: 4px 12px;
        border-radius: 20px;
        font-size: 14px;
    }

    .expense-list-body {
        padding: 20px;
        flex: 1;
        overflow-y: auto;
    }

    .expense-item {
        background: #fff;
        border-radius: var(--border-radius);
        padding: 20px;
        margin-bottom: 15px;
        transition: var(--transition);
        border: 2px solid transparent;
        position: relative;
    }

    .expense-item::before {
        content: '';
        position: absolute;
        left: 0;
        top: 0;
        bottom: 0;
        width: 4px;
        background: linear-gradient(180deg, var(--primary-color), var(--primary-dark));
        border-radius: 2px 0 0 2px;
        opacity: 0;
        transition: var(--transition);
    }

    .expense-item:hover {
        transform: translateX(5px);
        box-shadow: 0 6px 20px rgba(0, 0, 0, 0.1);
        border-color: var(--primary-light);
    }

    .expense-item:hover::before {
        opacity: 1;
    }

    .expense-header {
        display: flex;
        justify-content: space-between;
        align-items: flex-start;
        margin-bottom: 12px;
    }

    .expense-title {
        font-weight: 600;
        color: var(--dark-color);
        font-size: 16px;
        margin-bottom: 5px;
    }

    .expense-meta {
        display: flex;
        gap: 15px;
        font-size: 13px;
        color: #999;
        margin-bottom: 8px;
    }

    .expense-meta span {
        display: flex;
        align-items: center;
        gap: 5px;
    }

    .expense-meta i {
        color: var(--primary-color);
        font-size: 14px;
    }

    .expense-amount {
        font-size: 24px;
        font-weight: 700;
        color: var(--danger-color);
        text-align: right;
    }

    .expense-actions {
        display: flex;
        gap: 8px;
        margin-top: 15px;
    }

    .expense-actions button {
        padding: 8px 16px;
        border-radius: 8px;
        border: none;
        font-size: 13px;
        font-weight: 500;
        cursor: pointer;
        transition: var(--transition);
        display: flex;
        align-items: center;
        gap: 6px;
    }

    .btn-edit {
        background: linear-gradient(135deg, #ffc107, #e0a800);
        color: white;
    }

    .btn-edit:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(255, 193, 7, 0.3);
    }

    .btn-delete {
        background: linear-gradient(135deg, #dc3545, #c82333);
        color: white;
    }

    .btn-delete:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(220, 53, 69, 0.3);
    }

    .category-badge {
        display: inline-block;
        padding: 4px 12px;
        border-radius: 20px;
        font-size: 12px;
        font-weight: 600;
        text-transform: uppercase;
        letter-spacing: 0.5px;
    }

    .category-materials {
        background: linear-gradient(135deg, #d1ecf1, #bee5eb);
        color: #0c5460;
    }

    .category-labor {
        background: linear-gradient(135deg, #d4edda, #c3e6cb);
        color: #155724;
    }

    .category-equipment {
        background: linear-gradient(135deg, #fff3cd, #ffeeba);
        color: #856404;
    }

    .category-permits {
        background: linear-gradient(135deg, #d1ecf1, #bee5eb);
        color: #0c5460;
    }

    .category-miscellaneous {
        background: linear-gradient(135deg, #f8d7da, #f5c6cb);
        color: #721c24;
    }

    /* Empty State - Enhanced */
    .empty-state {
        text-align: center;
        padding: 60px 20px;
        color: #999;
    }

    .empty-state i {
        font-size: 64px;
        margin-bottom: 20px;
        color: #ddd;
    }

    .empty-state h3 {
        font-size: 20px;
        margin-bottom: 10px;
        color: #666;
    }

    .empty-state p {
        margin: 0;
        font-size: 14px;
    }

    /* Modal Styling - Enhanced */
    .modal-content {
        border-radius: var(--border-radius);
        border: none;
        box-shadow: 0 20px 40px rgba(0, 0, 0, 0.2);
    }

    .modal-header {
        background: linear-gradient(135deg, var(--primary-color), var(--primary-dark));
        color: white;
        border-radius: var(--border-radius) var(--border-radius) 0 0;
        border: none;
    }

    .modal-title {
        font-weight: 600;
    }

    .btn-close-white {
        filter: invert(1);
    }

    /* Alert styling - Enhanced */
    .alert-fixed {
        position: fixed;
        top: 90px;
        right: 30px;
        z-index: 1050;
        min-width: 300px;
        opacity: 0;
        transform: translateX(100%);
        transition: all 0.5s cubic-bezier(0.68, -0.55, 0.265, 1.55);
        border-radius: var(--border-radius);
        border: none;
        box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
    }

    .alert-fixed.show {
        opacity: 1;
        transform: translateX(0);
    }

    /* Alert Styles */
    .alert {
        border-radius: var(--border-radius);
        padding: 15px 20px;
        margin-bottom: 20px;
        border: none;
        display: flex;
        align-items: center;
    }
    
    .alert i {
        margin-right: 10px;
        font-size: 16px;
    }
    
    .alert-success {
        background-color: rgba(40, 167, 69, 0.1);
        color: var(--success-color);
        border-left: 4px solid var(--success-color);
    }

    /* Filter Tabs Styling */
    .filter-tabs {
        display: flex;
        gap: 10px;
        padding: 10px 20px;
        background: #fff;
        border-bottom: 1px solid #eee;
        overflow-x: auto;
    }
    .filter-tab {
        padding: 5px 15px;
        border-radius: 20px;
        font-size: 12px;
        font-weight: 600;
        cursor: pointer;
        border: 1px solid #eee;
        transition: var(--transition);
        white-space: nowrap;
    }
    .filter-tab.active {
        background-color: var(--primary-color);
        color: white;
        border-color: var(--primary-color);
    }

    /* Responsive */
    @media (max-width: 1200px) {
        .content-grid {
            grid-template-columns: 1fr;
        }
        
        .form-container {
            position: relative;
            top: 0;
        }
    }

    @media (max-width: 992px) {
        .stats-grid {
            grid-template-columns: repeat(2, 1fr);
        }
    }

    @media (max-width: 768px) {
        .mobile-menu-toggle {
            display: block;
        }
        
        .sidebar-nav {
            transform: translateX(-100%);
            width: 280px;
            z-index: 1001;
        }
        
        .sidebar-nav.show {
            transform: translateX(0);
        }
        
        .content-wrapper {
            margin-left: 0;
        }

        .overlay {
            z-index: 1000;
        }

        .overlay.show {
            display: block;
        }

        .content-header {
            padding: 15px 20px;
            flex-direction: column;
            align-items: flex-start;
        }

        .page-title {
            font-size: 20px;
            margin-bottom: 10px;
        }

        .main-content {
            padding: 20px;
        }

        .header {
            padding: 0 15px;
        }

        .stats-grid {
            grid-template-columns: 1fr;
        }

        .logo { font-size: 18px; }
        .logo i { font-size: 20px; }
        .user-name { display: none; }
        .user-avatar { width: 32px; height: 32px; font-size: 14px; }

        /* Fix Project Info Card stacking */
        .project-info-body .text-end {
            text-align: left !important;
            margin-top: 15px;
        }
        
        #loadProjectBtn {
            width: 100% !important;
            margin-top: 0 !important;
            justify-content: center;
        }
    }

    /* Custom scrollbar */
    ::-webkit-scrollbar {
        width: 8px;
        height: 8px;
    }

    ::-webkit-scrollbar-track {
        background: #f1f1f1;
    }

    ::-webkit-scrollbar-thumb {
        background: #ddd;
        border-radius: 4px;
    }

    ::-webkit-scrollbar-thumb:hover {
        background: #ccc;
    }

    /* Overlay for mobile menu */
    .overlay {
        display: none;
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background-color: rgba(0, 0, 0, 0.5);
        z-index: 998;
    }

    .overlay.show {
        display: block;
    }

    /* Dynamic Item Tables Styling */
    .order-spec-table { margin-top: 15px; border-radius: 8px; overflow: hidden; border: 1px solid #e2e8f0; width: 100%; }
    .order-spec-table table { margin-bottom: 0; font-size: 12px; width: 100%; }
    .order-spec-table th { background: #f8f9fa; color: #4a5568; font-weight: 700; text-transform: uppercase; font-size: 10px; border-bottom: 2px solid #e2e8f0; padding: 10px 12px; }
    .order-spec-table td { padding: 10px 12px; color: #2d3748; border-bottom: 1px solid #edf2f7; vertical-align: middle; }
    .num-cell { text-align: right; font-family: 'Inter', monospace; }
    </style>
</head>
<body>
    <!-- Header - Same as previous pages -->
    <header class="header">
        <button class="mobile-menu-toggle" id="mobileMenuToggle">
            <i class="bi bi-list"></i>
        </button>
        <a href="<?= BASE_URL ?>crmdashboard" class="logo">
            <img src="<?= BASE_URL ?>assets/logo.png" alt="ConstructCRM Logo" style="height: 60px; width: 85px;">
        </a>
        <div class="header-actions">
            <!-- User Dropdown -->
            <div class="user-dropdown" id="userDropdown">
                <div class="user-profile" id="userProfile">
                    <div class="user-avatar"><?php echo strtoupper(substr($user_name, 0, 1)); ?></div>
                    <span class="user-name"><?php echo htmlspecialchars($user_name); ?></span>
                    <i class="bi bi-chevron-down dropdown-arrow"></i>
                </div>
                <div class="user-dropdown-menu">
                    <a href="<?= BASE_URL ?>profile" class="dropdown-item">
                        <i class="bi bi-person"></i>
                        <span>Profile</span>
                    </a>
                    <a href="<?= BASE_URL ?>settings" class="dropdown-item">
                        <i class="bi bi-gear"></i>
                        <span>Settings</span>
                    </a>
                    <div class="dropdown-divider"></div>
                    <a href="<?= BASE_URL ?>signin?logout=true" class="dropdown-item">
                        <i class="bi bi-box-arrow-right"></i>
                        <span>Logout</span>
                    </a>
                </div>
            </div>
        </div>
    </header>

    <div class="main-container">
        <!-- Overlay for mobile -->
        <div class="overlay" id="overlay"></div>

        <!-- Sidebar Navigation - Same as previous pages -->
        <nav class="sidebar-nav" id="sidebarNav">
            <div class="nav-section">
                <div class="nav-title">Main</div>
                <ul class="nav-list">
                    <?php if (($_SESSION['user_role'] ?? '') === 'Admin'): ?>
                    <li class="nav-item">
                        <a href="<?= BASE_URL ?>crmdashboard" class="nav-link">
                            <i class="bi bi-speedometer2"></i>
                            <span>Dashboard</span>
                        </a>
                    </li>
                    <?php endif; ?>
                    <li class="nav-item">
                        <a href="<?= BASE_URL ?>dashboard" class="nav-link">
                            <i class="bi bi-grid-1x2-fill"></i>
                            <span>Client</span>
                        </a>
                    </li>
                    <li class="nav-item">
                        <a href="<?= BASE_URL ?>projectlist" class="nav-link">
                            <i class="bi bi-list-ul"></i>
                            <span>Project List</span>
                        </a>
                    </li>
                    <li class="nav-item">
                        <a href="<?= BASE_URL ?>designimages" class="nav-link">
                            <i class="bi bi-palette-fill"></i>
                            <span>Design images</span>
                        </a>
                    </li>
                    <li class="nav-item">
                        <a href="<?= BASE_URL ?>assignmentcalendar" class="nav-link">
                            <i class="bi bi-calendar-event-fill"></i>
                            <span>Assignment Calendar</span>
                        </a>
                    </li>
                    <?php if (($_SESSION['user_role'] ?? '') === 'Admin'): ?>
                    <li class="nav-item">
                        <a href="<?= BASE_URL ?>place_order" class="nav-link">
                            <i class="bi bi-cart-check"></i> 
                            <span>Place Order</span>
                        </a>
                    </li>
                    
                    <li class="nav-item">
                        <a href="<?= BASE_URL ?>financetracker" class="nav-link active">
                            <i class="bi bi-cash-stack"></i>
                            <span>Finance Tracker</span>
                        </a>
                    </li>
                    <?php endif; ?>
                    <li class="nav-item">
                        <a href="<?= BASE_URL ?>imagepin" class="nav-link">
                            <i class="bi bi-pin-map-fill"></i>
                            <span>Image Pin & Comment</span>
                        </a>
                    </li>
                    <?php if (($_SESSION['user_role'] ?? '') === 'Admin'): ?>
                    <li class="nav-item">
                        <a href="<?= BASE_URL ?>designcost" class="nav-link">
                            <i class="bi bi-palette-fill"></i>
                            <span>Designs Cost</span>
                        </a>
                    </li>
                    <?php endif; ?>
                </ul>
            </div>
            
            <div class="nav-section">
                <div class="nav-title">Management</div>
                <ul class="nav-list">
                    <li class="nav-item">
                        <a href="<?= BASE_URL ?>taskmanager" class="nav-link">
                            <i class="bi bi-check2-square"></i>
                            <span>Task Manager</span>
                        </a>
                    </li>
                    <?php if (($_SESSION['user_role'] ?? '') === 'Admin'): ?>
                    <li class="nav-item">
                        <a href="<?= BASE_URL ?>users" class="nav-link">
                            <i class="bi bi-people-fill"></i>
                            <span>Users</span>
                        </a>
                    </li>
                    <?php endif; ?>
                </ul>
            </div>
            
            <?php if (($_SESSION['user_role'] ?? '') === 'Admin'): ?>
            <div class="nav-section">
                <div class="nav-title">Vendor Management</div>
                <ul class="nav-list">
                    <li class="nav-item">
                        <a href="<?= BASE_URL ?>addvendors" class="nav-link">
                            <i class="bi bi-person-plus-fill"></i>
                            <span>Add New Vendor</span>
                        </a>
                    </li>
                    <li class="nav-item">
                        <a href="<?= BASE_URL ?>viewvendors" class="nav-link">
                            <i class="bi bi-card-list"></i>
                            <span>View All Vendors</span>
                        </a>
                    </li>
                </ul>
            </div>
            <?php endif; ?>
        </nav>

        <!-- Content Wrapper - Same as previous pages -->
        <div class="content-wrapper">
            <!-- Content Header -->
            <div class="content-header">
                <h1 class="page-title">Finance Tracker</h1>
                <nav aria-label="breadcrumb">
                    <ol class="breadcrumb">
                        <li class="breadcrumb-item"><a href="#">Home</a></li>
                        <li class="breadcrumb-item"><a href="#">Management</a></li>
                        <li class="breadcrumb-item active" aria-current="page">Finance Tracker</li>
                    </ol>
                </nav>
            </div>

            <!-- Main Content -->
            <div class="main-content">
                <!-- Project Selection -->
                <div class="project-info-card">
                    <div class="project-info-header">
                        <i class="bi bi-folder"></i> Select Project
                    </div>
                    <div class="project-info-body">
                        <div class="row align-items-center">
                            <div class="col-md-8">
                                <label for="projectSelect" class="form-label">Choose Project:</label>
                                <select class="form-select" id="projectSelect" name="projectSelect">
                                    <option value="" selected disabled>Select a project...</option>
                                    <?php echo $projectOptions; ?>
                                </select>
                            </div>
                            <div class="col-md-4 text-end">
                                <button class="btn btn-primary" id="loadProjectBtn" disabled style="width: 200px;margin-top: 26px;">
                                    <i class="bi bi-arrow-right-circle"></i> Load Project
                                </button>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Project Info Card -->
                <div class="project-info-card" id="selectedProjectInfo" style="display: <?php echo $selectedProject ? 'block' : 'none'; ?>;">
                    <div class="project-info-header">
                        Project Information
                    </div>
                    <div class="project-info-body">
                        <div class="project-name"><?php echo $selectedProject ? htmlspecialchars($selectedProject['project_name'] . ' - ' . $selectedProject['client_name']) : 'My Sample Project'; ?></div>
                        <div class="project-id"><?php echo $selectedProject ? htmlspecialchars($selectedProject['project_id_display']) : 'PRJ-001'; ?></div>
                    </div>
                </div>
                <!-- Summary Stats -->
                <div class="stats-grid">
                    <div class="stat-card">
                        <div class="stat-icon <?php echo $isVendorSpecificView ? 'total' : 'total'; ?>">
                            <i class="bi bi-cash-stack"></i>
                        </div>
                        <div class="stat-details">
                            <h3 id="totalExpense">₹<?php echo number_format($isVendorSpecificView ? $vendorTotalExpenses : $totalProjectExpense, 2); ?></h3>
                            <p><?php echo $isVendorSpecificView ? 'Total Vendor Expenses' : 'Total Expenses'; ?></p>
                        </div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-icon <?php echo $isVendorSpecificView ? 'materials' : 'materials'; ?>">
                            <i class="bi bi-box-seam"></i>
                        </div>
                        <div class="stat-details">
                            <h3 id="materialsExpense">₹<?php echo number_format($isVendorSpecificView ? $vendorPaidAmount : $totalProjectMaterialsExpense, 2); ?></h3>
                            <p><?php echo $isVendorSpecificView ? 'Vendor Paid Amount' : 'Materials Cost'; ?></p>
                        </div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-icon labor">
                            <i class="bi bi-people-fill"></i>
                        </div>
                        <div class="stat-details">
                            <h3 id="laborExpense">₹<?php echo number_format($isVendorSpecificView ? $vendorRemainingAmount : $totalProjectLaborExpense, 2); ?></h3>
                            <p><?php echo $isVendorSpecificView ? 'Vendor Remaining Amount' : 'Labor Cost'; ?></p>
                        </div>
                    </div>
                </div>

                <!-- Content Grid -->
                <div class="content-grid">
                    <!-- Form Container -->
                    <div class="form-container">
                        <div class="form-header">
                            <i class="bi bi-receipt-cutoff"></i>
                            <h4 class="form-title">Record New Expense</h4>
                        </div>
                        <div class="form-body">
                            <?php if ($prefilledOrder): ?>
                                <div class="alert alert-info py-2 small mb-3">
                                    <i class="bi bi-info-circle"></i> Paying for Order: <b>#<?php echo $prefilledOrder['id']; ?></b> (Order Balance: ₹<?php echo number_format($prefilledOrder['remaining_amount'], 2); ?>)<br>
                                    <i class="bi bi-wallet2"></i> Total Category Remaining: <b>₹<?php echo number_format($categoryRemainingBalance, 2); ?></b>
                                </div>
                            <?php endif; ?>
                            <form id="expense-form" method="POST" action="">
                                <input type="hidden" name="action" value="<?php echo $prefilledOrder ? 'process_order_payment' : 'add_expense'; ?>">
                                <input type="hidden" name="project_id" value="<?php echo $selectedProject ? $selectedProject['id'] : ''; ?>">
                                <input type="hidden" name="order_id" value="<?php echo $prefilledOrder ? $prefilledOrder['id'] : ''; ?>">
                                <div class="form-group">
                                    <label for="projectId" class="form-label">
                                        <i class="bi bi-tag"></i>
                                        Project ID
                                    </label>
                                    <input type="text" id="projectId" class="form-control" value="<?php echo $selectedProject ? htmlspecialchars($selectedProject['project_id_display']) : ''; ?>" readonly>
                                </div>
                                <div class="form-group">
                                    <label for="projectName" class="form-label">
                                        <i class="bi bi-building"></i>
                                        Project Name
                                    </label>
                                    <input type="text" id="projectName" class="form-control" value="<?php echo $selectedProject ? htmlspecialchars($selectedProject['project_name'] . ' - ' . $selectedProject['client_name']) : ''; ?>" readonly>
                                </div>
                                <div class="form-group">
                                    <label for="category" class="form-label">
                                        <i class="bi bi-folder"></i>
                                        Expense Category
                                    </label>
                                    <select id="category" name="category" class="form-select" required <?php echo $prefilledOrder ? 'disabled' : ''; ?>>
                                        <option value="">Select Category...</option>
                                        <option value="Materials" <?php echo ($prefilledOrder && $prefilledOrder['category'] == 'Materials') ? 'selected' : ''; ?>>Materials</option>
                                        <option value="Labor" <?php echo ($prefilledOrder && $prefilledOrder['category'] == 'Labor') ? 'selected' : ''; ?>>Labor/Contractor</option>
                                        <option value="Equipment" <?php echo ($prefilledOrder && $prefilledOrder['category'] == 'Equipment') ? 'selected' : ''; ?>>Equipment Rental</option>
                                        <option value="Permits" <?php echo ($prefilledOrder && $prefilledOrder['category'] == 'Permits') ? 'selected' : ''; ?>>Permits/Fees</option>
                                        <option value="Miscellaneous" <?php echo ($prefilledOrder && $prefilledOrder['category'] == 'Miscellaneous') ? 'selected' : ''; ?>>Miscellaneous</option>
                                    </select>
                                    <?php if($prefilledOrder): ?><input type="hidden" name="category" value="<?php echo $prefilledOrder['category']; ?>"><?php endif; ?>
                                </div>
                                <div class="form-group">
                                    <label for="description" class="form-label">
                                        <i class="bi bi-card-text"></i>
                                        Description
                                    </label>
                                    <?php 
                                        $descVal = '';
                                        if ($prefilledOrder) {
                                            $descVal = 'Payment for: ' . ($prefilledOrder['vendor_name'] ?? 'Labor') . ' (' . $prefilledOrder['item'] . ')';
                                        }
                                    ?>
                                    <input type="text" id="description" name="description" class="form-control" placeholder="Brief description" required value="<?php echo htmlspecialchars($descVal); ?>">
                                </div>
                                <div class="row">
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label for="unitCost" class="form-label">
                                                <i class="bi bi-currency-rupee"></i>
                                                <?php echo $prefilledOrder ? 'Payment Amount (₹)' : 'Unit Cost (₹)'; ?>
                                            </label>
                                            <input type="number" id="unitCost" name="unit_cost" class="form-control" placeholder="0.00" required min="0.01" step="0.01" <?php echo $prefilledOrder ? 'max="' . $prefilledOrder['remaining_amount'] . '"' : ''; ?>>
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label for="quantity" class="form-label">
                                                <i class="bi bi-hash"></i>
                                                Quantity
                                            </label>
                                            <input type="number" id="quantity" name="quantity" class="form-control" placeholder="1" required min="0.01" step="0.01" value="1" <?php echo $prefilledOrder ? 'readonly' : ''; ?>>
                                        </div>
                                    </div>
                                </div>
                                <div class="form-group">
                                    <label for="totalCost" class="form-label">
                                        <i class="bi bi-calculator"></i>
                                        Total Cost (₹)
                                    </label>
                                    <input type="text" id="totalCost" class="form-control" value="₹0.00" readonly style="background-color: var(--primary-light); font-weight: 600; color: var(--primary-color);">
                                </div>
                                <div class="row">
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label for="dateOfExpense" class="form-label">
                                                <i class="bi bi-calendar"></i>
                                                Date
                                            </label>
                                            <input type="date" id="dateOfExpense" name="entry_date" class="form-control" required value="<?php echo date('Y-m-d'); ?>">
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label for="recordedBy" class="form-label">
                                                <i class="bi bi-person"></i>
                                                Recorded By
                                            </label>
                                            <input type="text" id="recordedBy" name="recorded_by" class="form-control" placeholder="Your Name" required>
                                        </div>
                                    </div>
                                </div>
                                <div class="form-group">
                                    <button type="submit" class="btn btn-primary w-100" id="saveButton">
                                        <i class="bi bi-plus-circle"></i>
                                        <?php echo $prefilledOrder ? 'Process Payment' : 'Record Expense'; ?>
                                    </button>
                                </div>
                            </form>
                        </div>
                    </div>

                    <!-- Expense List Container -->
                    <div class="expense-list-container">
                        <div class="expense-list-header">
                            <h4 class="expense-list-title">
                                <i class="bi bi-list-check"></i>
                                Recent Transactions
                            </h4>
                            <span class="expense-count" id="expenseCount"><?php echo $expenseCount; ?></span>
                        </div>
                        <div class="filter-tabs" id="categoryFilter">
                            <div class="filter-tab active" data-category="all">All</div>
                            <div class="filter-tab" data-category="Materials">Materials</div>
                            <div class="filter-tab" data-category="Labor">Labor</div>
                            <div class="filter-tab" data-category="Equipment">Equipment</div>
                            <div class="filter-tab" data-category="Permits">Permits</div>
                            <div class="filter-tab" data-category="Miscellaneous">Misc</div>
                        </div>
                        <div class="expense-list-body">
                            <div id="expenseList">
                                <?php if (count($expenses) > 0): ?>
                                    <?php foreach ($expenses as $expense): ?>
                                        <div class="expense-item" data-category="<?php echo htmlspecialchars($expense['category']); ?>">
                                            <div class="expense-header">
                                                <div class="expense-title"><?php echo htmlspecialchars($expense['description']); ?></div>
                                                <div class="expense-amount">₹<?php echo number_format($expense['remaining_amount'] ?? $expense['amount'], 2); ?></div>
                                            </div>
                                            <div class="expense-meta">
                                                <span><i class="bi bi-calendar"></i> <?php echo date('M d, Y', strtotime($expense['entry_date'])); ?></span>
                                                <span><i class="bi bi-tag"></i> <?php echo htmlspecialchars($expense['category']); ?></span>
                                                <span><i class="bi bi-person"></i> <?php echo htmlspecialchars($expense['recorded_by'] ?? 'N/A'); ?></span>
                                            </div>

                                            <?php if (!empty($expense['item']) && !empty($expense['details'])): ?>
                                                <?php 
                                                    $details = json_decode($expense['details'], true) ?: [];
                                                    $itemType = strtolower($expense['item']);
                                                ?>
                                                <div class="order-spec-table table-responsive">
                                                    <table class="table table-sm table-bordered">
                                                        <?php if ($itemType === 'steel'): ?>
                                                            <thead><tr><th>MM</th><th>Nug</th><th>Weight</th><th>Rate</th><th>Total</th></tr></thead>
                                                            <tbody>
                                                                <?php 
                                                                $steel_items = $details['steel_items'] ?? (isset($details['weight']) ? [$details] : []);
                                                                foreach ($steel_items as $it): ?>
                                                                <tr>
                                                                    <td><?= htmlspecialchars($it['mm'] ?? '-') ?></td>
                                                                    <td class="num-cell"><?= htmlspecialchars($it['nug'] ?? '0') ?></td>
                                                                    <td class="num-cell"><?= htmlspecialchars($it['weight'] ?? '0') ?> kg</td>
                                                                    <td class="num-cell">₹<?= number_format($it['rate'] ?? 0, 2) ?></td>
                                                                    <td class="num-cell fw-bold">₹<?= number_format($it['total'] ?? 0, 2) ?></td>
                                                                </tr>
                                                                <?php endforeach; ?>
                                                            </tbody>
                                                        <?php elseif ($itemType === 'cement'): ?>
                                                            <thead><tr><th>Bag</th><th>Rate</th><th>Total</th></tr></thead>
                                                            <tbody>
                                                                <tr>
                                                                    <td class="num-cell"><?= htmlspecialchars($details['bag'] ?? '0') ?></td>
                                                                    <td class="num-cell">₹<?= number_format($details['rate'] ?? 0, 2) ?></td>
                                                                    <td class="num-cell fw-bold">₹<?= number_format($details['total'] ?? 0, 2) ?></td>
                                                                </tr>
                                                            </tbody>
                                                        <?php elseif ($itemType === 'tiles'): ?>
                                                            <thead><tr><th>Tile Name</th><th>Size</th><th>Tiles Box</th><th>Total Square Foot</th><th>Rate</th><th>Total</th></tr></thead>
                                                            <tbody>
                                                                <?php 
                                                                $tiles_items = $details['tiles_items'] ?? (isset($details['tiles_name']) ? [$details] : []);
                                                                foreach ($tiles_items as $it): ?>
                                                                <tr>
                                                                    <td><?= htmlspecialchars($it['tiles_name'] ?? '-') ?></td>
                                                                    <td><?= htmlspecialchars($it['size'] ?? '-') ?></td>
                                                                    <td class="num-cell"><?= htmlspecialchars($it['tiles_box'] ?? '0') ?></td>
                                                                    <td class="num-cell"><?= htmlspecialchars($it['total_square_foot'] ?? ($it['tiles_sqft'] ?? '0')) ?></td>
                                                                    <td class="num-cell">₹<?= number_format($it['rate'] ?? 0, 2) ?></td>
                                                                    <td class="num-cell fw-bold">₹<?= number_format($it['total'] ?? 0, 2) ?></td>
                                                                </tr>
                                                                <?php endforeach; ?>
                                                            </tbody>
                                                        <?php elseif ($itemType === 'etu' || $itemType === 'fero'): ?>
                                                            <thead><tr><th>Nug</th><th>Per Nug Rate</th><th>Total</th></tr></thead>
                                                            <tbody>
                                                                <tr>
                                                                    <td class="num-cell"><?= htmlspecialchars($details['nug'] ?? '0') ?></td>
                                                                    <td class="num-cell">₹<?= number_format($details['rate'] ?? 0, 2) ?></td>
                                                                    <td class="num-cell fw-bold">₹<?= number_format($details['total'] ?? 0, 2) ?></td>
                                                                </tr>
                                                            </tbody>
                                                        <?php elseif ($itemType === 'labor' || $expense['category'] === 'Labor'): ?>
                                                            <thead><tr><th>Labor Name</th><th>Rate</th><th>Total</th></tr></thead>
                                                            <tbody>
                                                                <tr>
                                                                    <td><?= htmlspecialchars($details['labor_name'] ?? '-') ?></td>
                                                                    <td class="num-cell">₹<?= number_format($details['rate'] ?? 0, 2) ?></td>
                                                                    <td class="num-cell fw-bold">₹<?= number_format($details['total'] ?? 0, 2) ?></td>
                                                                </tr>
                                                            </tbody>
                                                        <?php endif; ?>
                                                    </table>
                                                </div>
                                            <?php endif; ?>

                                            <?php if (!isset($_GET['order_id'])): ?>
                                                <div class="expense-actions">
                                                    <button class="btn-edit" onclick="editExpense(<?php echo $expense['id']; ?>)">
                                                        <i class="bi bi-pencil"></i> Edit
                                                    </button>
                                                    <button class="btn-delete" onclick="deleteExpense(<?php echo $expense['id']; ?>)">
                                                        <i class="bi bi-trash"></i> Delete
                                                    </button>
                                                </div>
                                            <?php endif; ?>
                                        </div>
                                    <?php endforeach; ?>
                                <?php else: ?>
                                    <div class="empty-state">
                                        <i class="bi bi-inbox"></i>
                                        <h3>No Transactions Found</h3>
                                        <p>Start tracking your project by adding your first transaction</p>
                                    </div>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Edit Expense Modal -->
    <div class="modal fade" id="editExpenseModal" tabindex="-1" aria-labelledby="editExpenseModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="editExpenseModalLabel">
                        <i class="bi bi-pencil-square me-2"></i>
                        Edit Expense
                    </h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form id="edit-expense-form">
                        <input type="hidden" id="editId" name="expense_id">
                        <div class="form-group">
                            <label for="editProjectId" class="form-label">Project ID</label>
                            <input type="text" id="editProjectId" class="form-control" required>
                        </div>
                        <div class="form-group">
                            <label for="editProjectName" class="form-label">Project Name</label>
                            <input type="text" id="editProjectName" class="form-control" required>
                        </div>
                        <div class="form-group">
                            <label for="editCategory" class="form-label">Expense Category</label>
                            <select id="editCategory" name="category" class="form-select" required>
                                <option value="Materials">Materials</option>
                                <option value="Labor">Labor/Contractor</option>
                                <option value="Equipment">Equipment Rental</option>
                                <option value="Permits">Permits/Fees</option>
                                <option value="Miscellaneous">Miscellaneous</option>
                            </select>
                        </div>
                        <div class="form-group">
                            <label for="editDescription" class="form-label">Description</label>
                            <input type="text" id="editDescription" name="description" class="form-control" required>
                        </div>
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="editUnitCost" class="form-label">Unit Cost (₹)</label>
                                    <input type="number" id="editUnitCost" name="unit_cost" class="form-control" required min="0.01" step="0.01">
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="editQuantity" class="form-label">Quantity</label>
                                    <input type="number" id="editQuantity" name="quantity" class="form-control" required min="0.01" step="0.01" value="1">
                                </div>
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="editCost" class="form-label">Total Cost (₹)</label>
                            <input type="number" id="editCost" name="amount" class="form-control" required min="0.01" step="0.01">
                        </div>
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="editDateOfExpense" class="form-label">Date</label>
                                    <input type="date" id="editDateOfExpense" name="entry_date" class="form-control" required>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="editRecordedBy" class="form-label">Recorded By</label>
                                    <input type="text" id="editRecordedBy" name="recorded_by" class="form-control" required>
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="button" class="btn btn-primary" id="saveEditButton">
                        <i class="bi bi-check-circle me-2"></i>
                        Save Changes
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Status Message -->
    <div id="top-status-message" class="alert-fixed alert d-none" role="alert"></div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>

    <script>
        // Project selector functionality
        document.addEventListener('DOMContentLoaded', function () {
            const projectSelect = document.getElementById('projectSelect');
            const loadProjectBtn = document.getElementById('loadProjectBtn');
            const sidebarNav = document.getElementById('sidebarNav');
            const overlay = document.getElementById('overlay');
            const mobileMenuToggle = document.getElementById('mobileMenuToggle');

            // Mobile menu toggle logic
            if (mobileMenuToggle && sidebarNav && overlay) {
                mobileMenuToggle.addEventListener('click', () => {
                    sidebarNav.classList.toggle('show');
                    overlay.classList.toggle('show');
                });

                overlay.addEventListener('click', () => {
                    sidebarNav.classList.remove('show');
                    overlay.classList.remove('show');
                });

                // Close sidebar when clicking a nav link on mobile
                document.querySelectorAll('.nav-link').forEach(link => {
                    link.addEventListener('click', () => {
                        if (window.innerWidth <= 768) {
                            sidebarNav.classList.remove('show');
                            overlay.classList.remove('show');
                        }
                    });
                });
            }

            // Enable/disable load button
            if (projectSelect) {
                projectSelect.addEventListener('change', () => {
                    loadProjectBtn.disabled = !projectSelect.value;
                });
            }
        });

        // Project data from database
        const projectData = {
            <?php echo $projectDataJS; ?>
        };

        // Handle load project button click
        document.getElementById('loadProjectBtn').addEventListener('click', () => {
            const selectedValue = projectSelect.value;
            if (selectedValue) {
                // Redirect to load the project
                window.location.href = `${selectedValue}`;
            }
        });

        // Unit Cost and Quantity auto-calculation
        const unitCostInput = document.getElementById('unitCost');
        const quantityInput = document.getElementById('quantity');
        const totalCostInput = document.getElementById('totalCost');

        function calculateTotalCost() {
            const unitCost = parseFloat(unitCostInput.value) || 0;
            const quantity = parseFloat(quantityInput.value) || 0;
            const total = unitCost * quantity;
            totalCostInput.value = '₹' + total.toFixed(2);
        }

        if (unitCostInput && quantityInput && totalCostInput) {
            unitCostInput.addEventListener('input', calculateTotalCost);
            quantityInput.addEventListener('input', calculateTotalCost);
        }

        // Edit expense functionality - Opens modal directly with AJAX
        async function editExpense(expenseId) {
            const projectId = '<?php echo $selectedProject ? $selectedProject['id'] : ''; ?>';
            
            if (!projectId) {
                showAlert('Please select a project first', 'danger');
                return;
            }
            
            try {
                const response = await fetch(`?action=get_expense&expense_id=${expenseId}&project_id=${projectId}`);
                const result = await response.json();
                
                if (result.success) {
                    const data = result.data;
                    
                    // Populate the edit form with expense data
                    document.getElementById('editId').value = data.id;
                    document.getElementById('editProjectId').value = '<?php echo $selectedProject ? $selectedProject['project_id_display'] : ''; ?>';
                    document.getElementById('editProjectName').value = '<?php echo $selectedProject ? addslashes($selectedProject['project_name'] . ' - ' . $selectedProject['client_name']) : ''; ?>';
                    document.getElementById('editCategory').value = data.category;
                    document.getElementById('editDescription').value = data.description;
                    document.getElementById('editUnitCost').value = data.unit_cost;
                    document.getElementById('editQuantity').value = data.quantity;
                    document.getElementById('editCost').value = data.amount;
                    document.getElementById('editDateOfExpense').value = data.entry_date;
                    document.getElementById('editRecordedBy').value = data.recorded_by || '';
                    
                    // Show the modal
                    const editModal = new bootstrap.Modal(document.getElementById('editExpenseModal'));
                    editModal.show();
                    
                    // Add auto-calculation for edit form
                    const editUnitCost = document.getElementById('editUnitCost');
                    const editQuantity = document.getElementById('editQuantity');
                    const editCost = document.getElementById('editCost');
                    
                    function calculateEditTotalCost() {
                        const unitCost = parseFloat(editUnitCost.value) || 0;
                        const quantity = parseFloat(editQuantity.value) || 0;
                        const total = unitCost * quantity;
                        editCost.value = total.toFixed(2);
                    }
                    
                    editUnitCost.addEventListener('input', calculateEditTotalCost);
                    editQuantity.addEventListener('input', calculateEditTotalCost);
                } else {
                    showAlert(result.message || 'Error loading expense data', 'danger');
                }
            } catch (error) {
                console.error('Error:', error);
                showAlert('Error loading expense data. Please try again.', 'danger');
            }
        }

        // Delete expense functionality
        function deleteExpense(expenseId) {
            if (confirm('Are you sure you want to delete this expense? This action cannot be undone.')) {
                // Create a form to submit delete request
                const form = document.createElement('form');
                form.method = 'POST';
                form.action = '';

                const actionInput = document.createElement('input');
                actionInput.type = 'hidden';
                actionInput.name = 'action';
                actionInput.value = 'delete_expense';

                const expenseIdInput = document.createElement('input');
                expenseIdInput.type = 'hidden';
                expenseIdInput.name = 'expense_id';
                expenseIdInput.value = expenseId;

                const projectIdInput = document.createElement('input');
                projectIdInput.type = 'hidden';
                projectIdInput.name = 'project_id';
                projectIdInput.value = '<?php echo $selectedProject ? $selectedProject['id'] : ''; ?>';

                form.appendChild(actionInput);
                form.appendChild(expenseIdInput);
                form.appendChild(projectIdInput);
                document.body.appendChild(form);
                form.submit();
            }
        }

    // Handle edit expense modal - Submit via AJAX without page refresh
    document.getElementById('saveEditButton').addEventListener('click', async () => {
        const form = document.getElementById('edit-expense-form');
        const formData = new FormData(form);

        // Add action and project_id
        formData.append('action', 'edit_expense');
        formData.append('project_id', '<?php echo $selectedProject ? $selectedProject['id'] : ''; ?>');

        // Get form values for dynamic update
        const expenseId = document.getElementById('editId').value;
        const description = document.getElementById('editDescription').value;
        const category = document.getElementById('editCategory').value;
        const amount = document.getElementById('editCost').value;
        const entryDate = document.getElementById('editDateOfExpense').value;
        const recordedBy = document.getElementById('editRecordedBy').value;

        // Submit via AJAX to avoid page refresh
        try {
            const response = await fetch('', {
                method: 'POST',
                body: formData
            });
            
            // Parse the JSON response
            const result = await response.json();
            
            // Check if update was successful
            if (result.success) {
                // Hide the modal properly
                const modalEl = document.getElementById('editExpenseModal');
                const modal = bootstrap.Modal.getInstance(modalEl);
                if (modal) {
                    modal.hide();
                } else {
                    // Fallback: manually hide modal if instance not found
                    $(modalEl).modal('hide');
                }
                
                // Remove modal backdrop manually if it exists
                setTimeout(() => {
                    const backdrop = document.querySelector('.modal-backdrop');
                    if (backdrop) {
                        backdrop.remove();
                    }
                    document.body.classList.remove('modal-open');
                    document.body.style.overflow = '';
                    document.body.style.paddingRight = '';
                }, 300);
                
                // Show success message
                showAlert(result.message || 'Expense updated successfully!', 'success');
                
                // Dynamically update the expense item in the list without page refresh
                updateExpenseInList(expenseId, description, category, amount, entryDate, recordedBy);
            } else {
                showAlert(result.message || 'Error updating expense. Please try again.', 'danger');
            }
        } catch (error) {
            console.error('Error:', error);
            showAlert('Error updating expense. Please try again.', 'danger');
        }
    });

    // Function to update expense item in the list dynamically
    function updateExpenseInList(expenseId, description, category, amount, entryDate, recordedBy) {
        const expenseItems = document.querySelectorAll('.expense-item');
        
        expenseItems.forEach(item => {
            // Check if this is the updated expense by looking at edit button onclick
            const editBtn = item.querySelector('.btn-edit');
            if (editBtn && editBtn.getAttribute('onclick').includes(expenseId)) {
                // Update the expense details
                const titleEl = item.querySelector('.expense-title');
                const amountEl = item.querySelector('.expense-amount');
                const metaSpans = item.querySelectorAll('.expense-meta span');
                
                if (titleEl) titleEl.textContent = description;
                if (amountEl) amountEl.textContent = '₹' + parseFloat(amount).toFixed(2);
                
                // Update meta information
                if (metaSpans.length >= 3) {
                    // Date
                    const dateSpan = metaSpans[0];
                    if (dateSpan) {
                        const date = new Date(entryDate);
                        dateSpan.innerHTML = '<i class="bi bi-calendar"></i> ' + date.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' });
                    }
                    // Category
                    const categorySpan = metaSpans[1];
                    if (categorySpan) {
                        categorySpan.innerHTML = '<i class="bi bi-tag"></i> ' + category;
                    }
                    // Recorded By
                    const recordedBySpan = metaSpans[2];
                    if (recordedBySpan) {
                        recordedBySpan.innerHTML = '<i class="bi bi-person"></i> ' + recordedBy;
                    }
                }
            }
        });
    }

    // Function to show alert message
    function showAlert(message, type) {
        const alertDiv = document.getElementById('top-status-message');
        alertDiv.innerHTML = '<i class="bi bi-' + (type === 'success' ? 'check-circle' : 'exclamation-triangle') + '"></i> ' + message;
        alertDiv.className = 'alert-fixed alert alert-' + type;
        alertDiv.classList.add('show');
        setTimeout(() => {
            alertDiv.classList.remove('show');
        }, 5000);
    }

        // Category filtering logic (Additive)
        const filterTabs = document.querySelectorAll('.filter-tab');
        const expenseItems = document.querySelectorAll('.expense-item');

        filterTabs.forEach(tab => {
            tab.addEventListener('click', () => {
                // UI Update
                filterTabs.forEach(t => t.classList.remove('active'));
                tab.classList.add('active');

                const category = tab.dataset.category;
                let visibleCount = 0;

                expenseItems.forEach(item => {
                    if (category === 'all' || item.dataset.category === category) {
                        item.style.display = 'block';
                        visibleCount++;
                    } else {
                        item.style.display = 'none';
                    }
                });
                
                document.getElementById('expenseCount').textContent = visibleCount;
            });
        });

        // User dropdown toggle
        document.getElementById('userProfile').addEventListener('click', (e) => {
            e.stopPropagation();
            document.getElementById('userDropdown').classList.toggle('show');
        });

        document.addEventListener('click', () => {
            document.getElementById('userDropdown').classList.remove('show');
        });

        // Show alert message if exists
        <?php if (!empty($alertMessage)): ?>
            const alertDiv = document.getElementById('top-status-message');
            alertDiv.innerHTML = '<i class="bi bi-<?php echo $alertType === 'success' ? 'check-circle' : 'exclamation-triangle'; ?>"></i> <?php echo addslashes($alertMessage); ?>';
            alertDiv.classList.add('alert-<?php echo $alertType; ?>');
            alertDiv.classList.add('show');
            setTimeout(() => {
                alertDiv.classList.remove('show');
            }, 5000);
        <?php endif; ?>

        // Auto-populate edit modal when editing expense
        <?php if ($editExpenseData): ?>
            document.addEventListener('DOMContentLoaded', function() {
                // Populate the edit form with expense data
                document.getElementById('editId').value = '<?php echo $editExpenseData['id']; ?>';
                document.getElementById('editProjectId').value = '<?php echo $selectedProject ? $selectedProject['project_id_display'] : ''; ?>';
                document.getElementById('editProjectName').value = '<?php echo $selectedProject ? addslashes($selectedProject['project_name'] . ' - ' . $selectedProject['client_name']) : ''; ?>';
                document.getElementById('editCategory').value = '<?php echo addslashes($editExpenseData['category']); ?>';
                document.getElementById('editDescription').value = '<?php echo addslashes($editExpenseData['description']); ?>';
                document.getElementById('editUnitCost').value = '<?php echo $editExpenseData['unit_cost']; ?>';
                document.getElementById('editQuantity').value = '<?php echo $editExpenseData['quantity']; ?>';
                document.getElementById('editCost').value = '<?php echo $editExpenseData['amount']; ?>';
                document.getElementById('editDateOfExpense').value = '<?php echo $editExpenseData['entry_date']; ?>';
                document.getElementById('editRecordedBy').value = '<?php echo addslashes($editExpenseData['recorded_by']); ?>';
                
                // Show the modal
                const editModal = new bootstrap.Modal(document.getElementById('editExpenseModal'));
                editModal.show();
            });
        <?php endif; ?>
    </script>
</body>
</html>