<?php
session_start(); // MAKE SURE SESSION_START IS NOT COMMENTED
if(!isset($_SESSION['username'])) {
    header("Location: ../login.php");
    exit();
}

include('../includes/db.php');

$success_message = "";
$error_message = "";

// Debug: Check if table exists
$table_check = mysqli_query($conn, "SHOW TABLES LIKE 'expenses'");
if(mysqli_num_rows($table_check) == 0) {
    // Create expenses table if not exists
    $create_table = "CREATE TABLE IF NOT EXISTS expenses (
        id INT(11) AUTO_INCREMENT PRIMARY KEY,
        title VARCHAR(200) NOT NULL,
        amount DECIMAL(10,2) NOT NULL,
        description TEXT,
        payment_method VARCHAR(50) DEFAULT 'cash',
        date_time VARCHAR(50) NOT NULL
    )";
    mysqli_query($conn, $create_table);
}

// Get bank accounts for dropdown
$bank_accounts_sql = "SELECT id, bank_name, account_title, balance FROM bank_accounts ORDER BY bank_name";
$bank_accounts_result = mysqli_query($conn, $bank_accounts_sql);

// Add Expense
if($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['add_expense'])) {
    $title = mysqli_real_escape_string($conn, trim($_POST['title']));
    $amount = mysqli_real_escape_string($conn, trim($_POST['amount']));
    $description = mysqli_real_escape_string($conn, trim($_POST['description']));
    $payment_method = mysqli_real_escape_string($conn, $_POST['payment_method']);
    $bank_id = isset($_POST['bank_id']) ? intval($_POST['bank_id']) : 0;
    $date_time = date('Y-m-d H:i:s');
    
    if(empty($title)) {
        $error_message = "Expense title is required!";
    } elseif(empty($amount) || !is_numeric($amount) || $amount <= 0) {
        $error_message = "Valid amount is required (must be greater than 0)!";
    } elseif($payment_method == 'bank' && empty($bank_id)) {
        $error_message = "Please select a bank account for bank payment!";
    } else {
        mysqli_begin_transaction($conn);
        
        try {
            // For bank payment, check bank balance first
            if($payment_method == 'bank' && $bank_id > 0) {
                $bank_check_sql = "SELECT balance FROM bank_accounts WHERE id = '$bank_id'";
                $bank_check_result = mysqli_query($conn, $bank_check_sql);
                $bank_data = mysqli_fetch_assoc($bank_check_result);
                if($bank_data['balance'] < $amount) {
                    throw new Exception("Insufficient bank balance! Available: Rs " . number_format($bank_data['balance'], 2));
                }
            }
            
            // Insert expense record
            $sql = "INSERT INTO expenses (title, amount, description, payment_method, date_time) 
                    VALUES ('$title', '$amount', '$description', '$payment_method', '$date_time')";
            
            if(!mysqli_query($conn, $sql)) {
                throw new Exception("Failed to add expense: " . mysqli_error($conn));
            }
            
            // For bank payment, deduct from bank account
            if($payment_method == 'bank' && $bank_id > 0) {
                // Update bank balance (deduct amount)
                $update_bank = "UPDATE bank_accounts SET balance = balance - $amount WHERE id = '$bank_id'";
                if(!mysqli_query($conn, $update_bank)) {
                    throw new Exception("Failed to update bank balance");
                }
                
                // Insert into bank book as withdrawal
                $bank_book_sql = "INSERT INTO bank_book (bank_id, entry_type, amount, description, reference_no, date_time) 
                                  VALUES ('$bank_id', 'Withdrawal', '$amount', 'Expense: $title', 'EXP-$title', '$date_time')";
                if(!mysqli_query($conn, $bank_book_sql)) {
                    throw new Exception("Failed to record bank transaction");
                }
            }
            
            mysqli_commit($conn);
            $success_message = "Expense added successfully! Amount: Rs " . number_format($amount, 2);
            
        } catch (Exception $e) {
            mysqli_rollback($conn);
            $error_message = "Error: " . $e->getMessage();
        }
    }
}

// Delete Expense
if(isset($_GET['delete'])) {
    $delete_id = mysqli_real_escape_string($conn, $_GET['delete']);
    
    // Get expense details to reverse bank transaction if needed
    $get_expense_sql = "SELECT amount, payment_method FROM expenses WHERE id='$delete_id'";
    $get_expense_result = mysqli_query($conn, $get_expense_sql);
    $expense_data = mysqli_fetch_assoc($get_expense_result);
    
    mysqli_begin_transaction($conn);
    
    try {
        $sql = "DELETE FROM expenses WHERE id='$delete_id'";
        if(!mysqli_query($conn, $sql)) {
            throw new Exception("Error deleting expense: " . mysqli_error($conn));
        }
        
        // If expense was paid via bank, we need to reverse the bank transaction
        // Note: This is a simplified approach. In production, you might want to mark as reversed instead.
        
        mysqli_commit($conn);
        $success_message = "Expense deleted successfully!";
        
    } catch (Exception $e) {
        mysqli_rollback($conn);
        $error_message = "Error: " . $e->getMessage();
    }
}

// Get all expenses
$sql = "SELECT * FROM expenses ORDER BY id DESC";
$result = mysqli_query($conn, $sql);

// Get total expenses
$total_sql = "SELECT SUM(amount) as total FROM expenses";
$total_result = mysqli_query($conn, $total_sql);
$total_expense = mysqli_fetch_assoc($total_result);
$total_expenses = ($total_expense['total']) ? $total_expense['total'] : 0;

// Get monthly expenses for current month
$current_month = date('Y-m');
$monthly_sql = "SELECT SUM(amount) as monthly_total FROM expenses WHERE date_time LIKE '$current_month%'";
$monthly_result = mysqli_query($conn, $monthly_sql);
$monthly_expense = mysqli_fetch_assoc($monthly_result);
$monthly_total = ($monthly_expense['monthly_total']) ? $monthly_expense['monthly_total'] : 0;

// Get expense statistics
$total_expense_count = mysqli_num_rows($result);
$avg_expense = ($total_expense_count > 0) ? $total_expenses / $total_expense_count : 0;
?>

<?php include('../includes/log.php'); ?>
<?php include('../includes/sd.php'); ?>

<div class="expenses-container">
    <!-- Page Header -->
    <div class="page-header">
        <div class="header-left">
            <h2><i class="fas fa-file-invoice-dollar"></i> Expenses Management</h2>
            <p>Track and manage all business expenses</p>
        </div>
        <div class="header-right">
            <div class="stats-badge">
                <i class="fas fa-chart-line"></i>
                <span><?php echo $total_expense_count; ?> Total Expenses</span>
            </div>
        </div>
    </div>

    <!-- Statistics Cards -->
    <div class="row g-4 mb-4">
        <div class="col-md-4">
            <div class="stat-card">
                <div class="stat-icon">
                    <i class="fas fa-chart-line"></i>
                </div>
                <div class="stat-info">
                    <h3>Rs <?php echo number_format($total_expenses, 2); ?></h3>
                    <p>Total Expenses</p>
                    <span class="stat-trend">All Time</span>
                </div>
            </div>
        </div>
        <div class="col-md-4">
            <div class="stat-card">
                <div class="stat-icon">
                    <i class="fas fa-calendar-month"></i>
                </div>
                <div class="stat-info">
                    <h3>Rs <?php echo number_format($monthly_total, 2); ?></h3>
                    <p>This Month</p>
                    <span class="stat-trend"><?php echo date('F Y'); ?></span>
                </div>
            </div>
        </div>
        <div class="col-md-4">
            <div class="stat-card">
                <div class="stat-icon">
                    <i class="fas fa-calculator"></i>
                </div>
                <div class="stat-info">
                    <h3>Rs <?php echo number_format($avg_expense, 2); ?></h3>
                    <p>Average Expense</p>
                    <span class="stat-trend">Per Transaction</span>
                </div>
            </div>
        </div>
    </div>

    <!-- Alerts -->
    <?php if($success_message): ?>
        <div class="alert-custom alert-success">
            <i class="fas fa-check-circle"></i> <?php echo $success_message; ?>
            <button class="close-alert" onclick="this.parentElement.remove();">&times;</button>
        </div>
    <?php endif; ?>
    
    <?php if($error_message): ?>
        <div class="alert-custom alert-danger">
            <i class="fas fa-exclamation-triangle"></i> <?php echo $error_message; ?>
            <button class="close-alert" onclick="this.parentElement.remove();">&times;</button>
        </div>
    <?php endif; ?>
    
    <div class="row g-4">
        <!-- Add Expense Form -->
        <div class="col-xl-4 col-lg-5">
            <div class="form-card">
                <div class="form-card-header">
                    <i class="fas fa-plus-circle"></i>
                    <h4>Add New Expense</h4>
                </div>
                <div class="form-card-body">
                    <form method="POST" action="" id="expenseForm">
                        <div class="input-group-custom">
                            <label><i class="fas fa-tag"></i> Expense Title <span class="required">*</span></label>
                            <input type="text" name="title" class="form-control-modern" required placeholder="e.g., Electricity Bill, Salary, Maintenance">
                            <small class="input-help">Give a clear title for this expense</small>
                        </div>
                        
                        <div class="input-group-custom">
                            <label><i class="fas fa-rupee-sign"></i> Amount (Rs) <span class="required">*</span></label>
                            <input type="number" step="0.01" name="amount" id="amount" class="form-control-modern" required placeholder="Enter amount" onkeyup="updateBankInfo()">
                            <small class="input-help">Enter the expense amount</small>
                        </div>
                        
                        <div class="input-group-custom">
                            <label><i class="fas fa-money-bill-wave"></i> Payment Method <span class="required">*</span></label>
                            <select name="payment_method" id="payment_method" class="form-control-modern" required onchange="toggleBankField()">
                                <option value="cash">Cash</option>
                                <option value="bank">Bank (Direct Withdrawal)</option>
                            </select>
                        </div>
                        
                        <!-- Bank Account Selection (shown only when bank is selected) -->
                        <div class="input-group-custom" id="bank_div" style="display: none;">
                            <label><i class="fas fa-university"></i> Select Bank Account <span class="required">*</span></label>
                            <select name="bank_id" id="bank_id" class="form-control-modern" onchange="updateBankInfo()">
                                <option value="">-- Select Bank Account --</option>
                                <?php 
                                mysqli_data_seek($bank_accounts_result, 0);
                                while($bank = mysqli_fetch_assoc($bank_accounts_result)): 
                                ?>
                                    <option value="<?php echo $bank['id']; ?>"
                                            data-bank-balance="<?php echo $bank['balance']; ?>"
                                            data-bank-name="<?php echo htmlspecialchars($bank['bank_name']); ?>">
                                        <?php echo htmlspecialchars($bank['bank_name']); ?> - 
                                        <?php echo htmlspecialchars($bank['account_title']); ?> 
                                        (Balance: Rs <?php echo number_format($bank['balance'], 2); ?>)
                                    </option>
                                <?php endwhile; ?>
                            </select>
                            <small class="input-help">Amount will be deducted from selected bank account</small>
                        </div>
                        
                        <!-- Bank Info Box (shown when bank is selected) -->
                        <div class="bank-info-box" id="bankInfoBox" style="display: none;">
                            <div class="info-row">
                                <span><i class="fas fa-university"></i> Bank Balance:</span>
                                <strong id="displayBankBalance">Rs 0.00</strong>
                            </div>
                            <div class="info-row" style="color: #dc3545;">
                                <span><i class="fas fa-arrow-down"></i> After Withdrawal:</span>
                                <strong id="displayNewBankBalance">Rs 0.00</strong>
                            </div>
                        </div>
                        
                        <div class="input-group-custom">
                            <label><i class="fas fa-align-left"></i> Description</label>
                            <textarea name="description" class="form-control-modern" rows="3" placeholder="Optional description"></textarea>
                            <small class="input-help">Add any additional details (optional)</small>
                        </div>
                        
                        <button type="submit" name="add_expense" class="btn-submit">
                            <i class="fas fa-save"></i> Add Expense
                        </button>
                    </form>
                </div>
            </div>
            
            <!-- Expense Tips Card -->
            <div class="info-card">
                <div class="info-card-header">
                    <i class="fas fa-lightbulb"></i>
                    <h5>Expense Tracking Tips</h5>
                </div>
                <div class="info-card-body">
                    <div class="info-item">
                        <span><i class="fas fa-tag"></i> Categorize expenses</span>
                        <span>Use clear titles</span>
                    </div>
                    <div class="info-item">
                        <span><i class="fas fa-rupee-sign"></i> Track regularly</span>
                        <span>Monitor spending</span>
                    </div>
                    <div class="info-item">
                        <span><i class="fas fa-chart-line"></i> Review monthly</span>
                        <span>Analyze trends</span>
                    </div>
                    <div class="info-item">
                        <span><i class="fas fa-print"></i> Keep receipts</span>
                        <span>For records</span>
                    </div>
                    <div class="info-item">
                        <span><i class="fas fa-university"></i> Bank expenses</span>
                        <span>Track from bank</span>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- Expenses List -->
        <div class="col-xl-8 col-lg-7">
            <div class="table-card">
                <div class="table-card-header">
                    <div class="header-info">
                        <i class="fas fa-list"></i>
                        <h4>Expenses List</h4>
                    </div>
                    <div class="table-search">
                        <i class="fas fa-search"></i>
                        <input type="text" id="tableSearch" placeholder="Search expenses..." class="search-input">
                    </div>
                </div>
                <div class="table-card-body">
                    <div class="table-responsive">
                        <table class="modern-table" id="expensesTable">
                            <thead>
                                <tr>
                                    <th>ID</th>
                                    <th>Title</th>
                                    <th>Amount (Rs)</th>
                                    <th>Payment Method</th>
                                    <th>Date</th>
                                    <th>Description</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if(mysqli_num_rows($result) > 0): ?>
                                    <?php while($row = mysqli_fetch_assoc($result)): ?>
                                        <tr>
                                            <td data-label="ID">#<?php echo $row['id']; ?></td>
                                            <td data-label="Title">
                                                <div class="expense-title-cell">
                                                    <i class="fas fa-receipt"></i>
                                                    <strong><?php echo htmlspecialchars($row['title']); ?></strong>
                                                </div>
                                             </div>
                                            <td data-label="Amount">
                                                <div class="amount-cell">
                                                    <strong>Rs <?php echo number_format($row['amount'], 2); ?></strong>
                                                </div>
                                             </div>
                                            <td data-label="Payment Method">
                                                <span class="method-badge <?php echo $row['payment_method'] == 'bank' ? 'bank' : 'cash'; ?>">
                                                    <i class="fas <?php echo $row['payment_method'] == 'bank' ? 'fa-university' : 'fa-money-bill-wave'; ?>"></i>
                                                    <?php echo ucfirst($row['payment_method'] ?: 'cash'); ?>
                                                </span>
                                             </div>
                                            <td data-label="Date">
                                                <div class="date-cell">
                                                    <i class="fas fa-calendar"></i>
                                                    <?php echo date('d-m-Y', strtotime($row['date_time'])); ?>
                                                    <small><?php echo date('H:i', strtotime($row['date_time'])); ?></small>
                                                </div>
                                             </div>
                                            <td data-label="Description">
                                                <div class="description-cell">
                                                    <?php echo htmlspecialchars($row['description']) ?: '<span class="text-muted">-</span>'; ?>
                                                </div>
                                             </div>
                                            <td data-label="Actions">
                                                <div class="action-buttons">
                                                    <a href="?delete=<?php echo $row['id']; ?>" 
                                                       class="btn-action btn-delete" 
                                                       onclick="return confirm('Delete this expense? This action cannot be undone!')"
                                                       title="Delete Expense">
                                                        <i class="fas fa-trash"></i>
                                                    </a>
                                                </div>
                                             </div>
                                        </tr>
                                    <?php endwhile; ?>
                                <?php else: ?>
                                    <tr>
                                        <td colspan="7" class="text-center empty-state">
                                            <i class="fas fa-file-invoice-dollar"></i>
                                            <p>No expenses found</p>
                                            <small>Click "Add New Expense" to record your first expense</small>
                                         </div>
                                    </tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<style>
/* Expenses Page Styles */
@import url('https://fonts.googleapis.com/css2?family=Quicksand:wght@300;400;500;600;700&display=swap');

* {
    font-family: 'Quicksand', sans-serif;
}

/* Headings use Times New Roman */
h1, h2, h3, h4, h5, h6,
.page-header h2,
.stat-info h3,
.form-card-header h4,
.header-info h4,
.modern-table th {
    font-family: 'Times New Roman', serif;
}

.expenses-container {
    padding: 0;
}

/* Page Header */
.page-header {
    background: linear-gradient(135deg, #A04657 0%, #6b2a36 100%);
    border-radius: 20px;
    padding: 25px 30px;
    margin-bottom: 30px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    color: #fff;
}

.page-header h2 {
    color: #fff;
    margin: 0 0 8px 0;
    font-size: 28px;
}

.page-header p {
    color: rgba(255,255,255,0.95);
    margin: 0;
    font-size: 14px;
    font-weight: 500;
}

.stats-badge {
    background: rgba(255,255,255,0.2);
    padding: 12px 20px;
    border-radius: 15px;
    font-weight: 600;
    font-size: 14px;
}

/* Statistics Cards */
.stat-card {
    background: #fff;
    border-radius: 20px;
    padding: 20px;
    display: flex;
    align-items: center;
    gap: 20px;
    box-shadow: 0 2px 10px rgba(0,0,0,0.05);
    transition: all 0.3s;
    border-left: 4px solid #A04657;
}

.stat-card:hover {
    transform: translateY(-3px);
    box-shadow: 0 5px 20px rgba(160,70,87,0.15);
}

.stat-icon {
    width: 60px;
    height: 60px;
    background: rgba(160,70,87,0.1);
    border-radius: 15px;
    display: flex;
    align-items: center;
    justify-content: center;
}

.stat-icon i {
    font-size: 28px;
    color: #A04657;
}

.stat-info h3 {
    font-size: 24px;
    margin: 0;
    font-weight: bold;
}

.stat-info p {
    margin: 5px 0 0;
    color: #555;
    font-size: 13px;
    font-weight: 600;
}

.stat-trend {
    font-size: 11px;
    color: #999;
    font-weight: 500;
}

/* Alert Styles */
.alert-custom {
    padding: 15px 20px;
    border-radius: 12px;
    margin-bottom: 20px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    animation: slideIn 0.3s ease;
    font-weight: 600;
}

@keyframes slideIn {
    from { transform: translateY(-20px); opacity: 0; }
    to { transform: translateY(0); opacity: 1; }
}

.alert-success {
    background: #d4edda;
    color: #155724;
    border-left: 4px solid #28a745;
}

.alert-danger {
    background: #f8d7da;
    color: #721c24;
    border-left: 4px solid #dc3545;
}

.close-alert {
    background: none;
    border: none;
    font-size: 24px;
    cursor: pointer;
    opacity: 0.5;
    transition: opacity 0.3s;
}

.close-alert:hover {
    opacity: 1;
}

/* Form Card */
.form-card {
    background: #fff;
    border-radius: 20px;
    overflow: hidden;
    box-shadow: 0 5px 20px rgba(0,0,0,0.05);
    margin-bottom: 20px;
}

.form-card-header {
    background: linear-gradient(135deg, #A04657 0%, #6b2a36 100%);
    padding: 20px;
    display: flex;
    align-items: center;
    gap: 12px;
    color: #fff;
}

.form-card-header i {
    font-size: 24px;
}

.form-card-header h4 {
    margin: 0;
    font-size: 18px;
    color: #fff;
}

.form-card-body {
    padding: 25px;
}

.input-group-custom {
    margin-bottom: 20px;
}

.input-group-custom label {
    display: block;
    margin-bottom: 8px;
    font-weight: 700;
    color: #333;
    font-size: 14px;
}

.input-group-custom label i {
    color: #A04657;
    margin-right: 8px;
}

.required {
    color: #dc3545;
}

.form-control-modern {
    width: 100%;
    padding: 12px 15px;
    border: 2px solid #e0e0e0;
    border-radius: 10px;
    font-size: 14px;
    transition: all 0.3s;
    font-weight: 500;
}

.form-control-modern:focus {
    border-color: #A04657;
    outline: none;
    box-shadow: 0 0 0 3px rgba(160,70,87,0.1);
}

.input-help {
    display: block;
    font-size: 11px;
    color: #999;
    margin-top: 5px;
    font-weight: 500;
}

.btn-submit {
    width: 100%;
    padding: 14px;
    background: linear-gradient(135deg, #A04657 0%, #6b2a36 100%);
    color: #fff;
    border: none;
    border-radius: 10px;
    font-weight: 700;
    font-size: 16px;
    cursor: pointer;
    transition: all 0.3s;
}

.btn-submit:hover {
    transform: translateY(-2px);
    box-shadow: 0 5px 15px rgba(160,70,87,0.3);
}

/* Bank Info Box */
.bank-info-box {
    background: #ffebee;
    border-radius: 12px;
    padding: 12px 15px;
    margin-bottom: 20px;
    border-left: 4px solid #dc3545;
}

.bank-info-box .info-row {
    display: flex;
    justify-content: space-between;
    margin-bottom: 6px;
    font-size: 13px;
}

.bank-info-box .info-row:last-child {
    margin-bottom: 0;
}

/* Method Badge */
.method-badge {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    padding: 4px 12px;
    border-radius: 20px;
    font-size: 12px;
    font-weight: 600;
}

.method-badge.cash {
    background: #e8f5e9;
    color: #2e7d32;
}

.method-badge.bank {
    background: #ffebee;
    color: #c62828;
}

/* Info Card */
.info-card {
    background: #f8f9fa;
    border-radius: 15px;
    padding: 20px;
}

.info-card-header {
    display: flex;
    align-items: center;
    gap: 10px;
    margin-bottom: 15px;
}

.info-card-header i {
    font-size: 20px;
    color: #A04657;
}

.info-card-header h5 {
    margin: 0;
    font-size: 16px;
}

.info-item {
    display: flex;
    justify-content: space-between;
    padding: 10px 0;
    border-bottom: 1px solid #e0e0e0;
    font-size: 13px;
    font-weight: 500;
}

.info-item:last-child {
    border-bottom: none;
}

.info-item span:first-child i {
    margin-right: 8px;
    color: #A04657;
}

/* Table Card */
.table-card {
    background: #fff;
    border-radius: 20px;
    overflow: hidden;
    box-shadow: 0 5px 20px rgba(0,0,0,0.05);
}

.table-card-header {
    padding: 20px;
    border-bottom: 1px solid #f0f0f0;
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-wrap: wrap;
    gap: 15px;
}

.header-info {
    display: flex;
    align-items: center;
    gap: 10px;
}

.header-info i {
    font-size: 20px;
    color: #A04657;
}

.header-info h4 {
    margin: 0;
    font-size: 18px;
}

.table-search {
    position: relative;
}

.table-search i {
    position: absolute;
    left: 12px;
    top: 50%;
    transform: translateY(-50%);
    color: #999;
}

.search-input {
    padding: 10px 15px 10px 40px;
    border: 2px solid #e0e0e0;
    border-radius: 10px;
    width: 250px;
    transition: all 0.3s;
    font-weight: 500;
}

.search-input:focus {
    border-color: #A04657;
    outline: none;
}

/* Modern Table */
.modern-table {
    width: 100%;
    border-collapse: collapse;
}

.modern-table th {
    padding: 15px;
    background: #f8f9fa;
    font-weight: 700;
    color: #444;
    font-size: 13px;
}

.modern-table td {
    padding: 15px;
    border-bottom: 1px solid #f0f0f0;
    vertical-align: middle;
    font-weight: 500;
    color: #333;
}

.modern-table tr:hover {
    background: #fafafa;
}

.expense-title-cell {
    display: flex;
    align-items: center;
    gap: 8px;
}

.expense-title-cell i {
    color: #A04657;
}

.amount-cell strong {
    color: #dc3545;
    font-size: 15px;
}

.date-cell {
    display: flex;
    flex-direction: column;
    font-size: 12px;
}

.date-cell i {
    margin-right: 5px;
    color: #999;
}

.date-cell small {
    color: #999;
    margin-left: 18px;
    font-size: 10px;
}

.description-cell {
    max-width: 200px;
    word-break: break-word;
    font-size: 12px;
}

.description-cell .text-muted {
    color: #999;
}

/* Action Buttons */
.action-buttons {
    display: flex;
    gap: 8px;
}

.btn-action {
    width: 32px;
    height: 32px;
    border-radius: 8px;
    display: flex;
    align-items: center;
    justify-content: center;
    text-decoration: none;
    transition: all 0.3s;
}

.btn-delete {
    background: #fee;
    color: #dc3545;
}

.btn-delete:hover {
    background: #dc3545;
    color: #fff;
    transform: scale(1.05);
}

.empty-state {
    padding: 50px !important;
    text-align: center;
}

.empty-state i {
    font-size: 48px;
    color: #A04657;
    margin-bottom: 15px;
}

.empty-state p {
    margin: 0;
    color: #666;
    font-weight: 600;
}

.empty-state small {
    color: #999;
    font-weight: 500;
}

/* Responsive */
@media (max-width: 768px) {
    .page-header {
        flex-direction: column;
        text-align: center;
    }
    
    .table-card-header {
        flex-direction: column;
    }
    
    .search-input {
        width: 100%;
    }
    
    .modern-table th {
        display: none;
    }
    
    .modern-table td {
        display: block;
        text-align: right;
        padding-left: 50%;
        position: relative;
    }
    
    .modern-table td::before {
        content: attr(data-label);
        position: absolute;
        left: 15px;
        width: 45%;
        text-align: left;
        font-weight: 700;
        color: #555;
    }
    
    .action-buttons {
        justify-content: flex-end;
    }
}

/* Scrollbar */
::-webkit-scrollbar {
    width: 8px;
    height: 8px;
}

::-webkit-scrollbar-track {
    background: #f1f1f1;
}

::-webkit-scrollbar-thumb {
    background: #A04657;
    border-radius: 4px;
}

::-webkit-scrollbar-thumb:hover {
    background: #6b2a36;
}
</style>

<script>
// Toggle bank field based on payment method
function toggleBankField() {
    const paymentMethod = document.getElementById('payment_method').value;
    const bankDiv = document.getElementById('bank_div');
    const bankInfoBox = document.getElementById('bankInfoBox');
    const isBank = (paymentMethod === 'bank');
    
    if(bankDiv) {
        bankDiv.style.display = isBank ? 'block' : 'none';
    }
    if(bankInfoBox) {
        bankInfoBox.style.display = isBank ? 'block' : 'none';
    }
    
    if(isBank) {
        document.getElementById('bank_id')?.setAttribute('required', 'required');
        updateBankInfo();
    } else {
        document.getElementById('bank_id')?.removeAttribute('required');
    }
}

// Update bank information
function updateBankInfo() {
    const bankSelect = document.getElementById('bank_id');
    if(!bankSelect) return;
    
    const selectedOption = bankSelect.options[bankSelect.selectedIndex];
    const bankBalance = parseFloat(selectedOption.getAttribute('data-bank-balance')) || 0;
    const amount = parseFloat(document.getElementById('amount')?.value) || 0;
    
    document.getElementById('displayBankBalance').innerHTML = 'Rs ' + bankBalance.toFixed(2);
    
    const newBalance = bankBalance - amount;
    const newBalanceSpan = document.getElementById('displayNewBankBalance');
    newBalanceSpan.innerHTML = 'Rs ' + newBalance.toFixed(2);
    
    if(amount > bankBalance) {
        newBalanceSpan.style.color = '#dc3545';
        newBalanceSpan.innerHTML += ' (Insufficient Balance!)';
    } else {
        newBalanceSpan.style.color = '#dc3545';
    }
}

// Table search functionality
document.getElementById('tableSearch').addEventListener('keyup', function() {
    let searchValue = this.value.toLowerCase();
    let table = document.getElementById('expensesTable');
    let rows = table.getElementsByTagName('tr');
    
    for (let i = 1; i < rows.length; i++) {
        let row = rows[i];
        let text = row.textContent.toLowerCase();
        if (text.includes(searchValue)) {
            row.style.display = '';
        } else {
            row.style.display = 'none';
        }
    }
});

// Add event listeners
document.getElementById('amount')?.addEventListener('input', function() {
    if(document.getElementById('payment_method')?.value === 'bank') {
        updateBankInfo();
    }
});

document.getElementById('bank_id')?.addEventListener('change', updateBankInfo);

// Initialize on page load
document.addEventListener('DOMContentLoaded', function() {
    toggleBankField();
});

// Auto-hide alerts after 5 seconds
document.querySelectorAll('.alert-custom').forEach(alert => {
    setTimeout(() => {
        if(alert) alert.style.opacity = '0';
        setTimeout(() => {
            if(alert && alert.parentElement) alert.remove();
        }, 300);
    }, 5000);
});
</script>

<?php include('../includes/ft.php'); ?>