<?php
// admin/accounts/expenses.php
require_once __DIR__ . '/../../includes/config.php';
require_once __DIR__ . '/../../includes/functions.php';

if (!isAdmin()) {
    header('Location: ../login.php');
    exit;
}

// Handle Add Expense
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_expense'])) {
    $category = sanitize($_POST['category'] ?? '');
    $description = sanitize($_POST['description'] ?? '');
    $amount = floatval($_POST['amount'] ?? 0);
    $payment_method = sanitize($_POST['payment_method'] ?? 'cash');
    $reference_no = sanitize($_POST['reference_no'] ?? '');
    $expense_date = $_POST['expense_date'] ?? date('Y-m-d');
    $note = sanitize($_POST['note'] ?? '');
    $vendor_id = isset($_POST['vendor_id']) && !empty($_POST['vendor_id']) ? intval($_POST['vendor_id']) : null;
    $po_id = isset($_POST['po_id']) && !empty($_POST['po_id']) ? intval($_POST['po_id']) : null;
    
    if (empty($category)) {
        $error_msg = 'Category is required';
    } elseif (empty($description)) {
        $error_msg = 'Description is required';
    } elseif ($amount <= 0) {
        $error_msg = 'Amount must be greater than 0';
    } else {
        $expense_no = 'EXP-' . date('Ymd') . '-' . rand(1000, 9999);
        $stmt = $pdo->prepare("INSERT INTO expenses 
            (expense_no, category, vendor_id, po_id, description, amount, payment_method, reference_no, expense_date, note, created_by) 
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
        $stmt->execute([
            $expense_no, $category, $vendor_id, $po_id, $description, $amount, 
            $payment_method, $reference_no, $expense_date, $note, $_SESSION['admin_id']
        ]);
        $_SESSION['success_msg'] = 'Expense added successfully!';
        header('Location: expenses.php');
        exit;
    }
}

// Handle Delete via AJAX
if (isset($_POST['delete_id'])) {
    $delete_id = intval($_POST['delete_id']);
    $stmt = $pdo->prepare("DELETE FROM expenses WHERE id = ?");
    $stmt->execute([$delete_id]);
    echo json_encode(['success' => true, 'message' => 'Expense deleted']);
    exit;
}

// Get expenses with vendor names
$stmt = $pdo->query("SELECT e.*, v.name as vendor_name 
                     FROM expenses e 
                     LEFT JOIN vendors v ON e.vendor_id = v.id 
                     ORDER BY e.created_at DESC");
$expenses = $stmt->fetchAll();

// Get vendors for dropdown
$vendors = $pdo->query("SELECT id, name FROM vendors WHERE status = 1 ORDER BY name")->fetchAll();

// Get totals
$stmt = $pdo->query("SELECT COALESCE(SUM(amount), 0) as total FROM expenses WHERE DATE(expense_date) <= CURDATE()");
$total_expenses = $stmt->fetch()['total'];

$stmt = $pdo->query("SELECT COALESCE(SUM(amount), 0) as total FROM expenses WHERE MONTH(expense_date) = MONTH(CURDATE()) AND YEAR(expense_date) = YEAR(CURDATE())");
$monthly_expenses = $stmt->fetch()['total'];

$success_msg = $_SESSION['success_msg'] ?? '';
$error_msg = $_SESSION['error_msg'] ?? '';
unset($_SESSION['success_msg']);
unset($_SESSION['error_msg']);

include '../header.php';
?>

<style>
.account-nav {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
    margin-bottom: 20px;
    padding: 15px;
    background: #fff;
    border-radius: 12px;
    box-shadow: 0 1px 3px rgba(0,0,0,0.1);
}

.account-nav a {
    padding: 8px 20px;
    border-radius: 8px;
    color: #64748b;
    text-decoration: none;
    transition: all 0.3s ease;
    font-size: 14px;
}

.account-nav a:hover,
.account-nav a.active {
    background: #047dc3;
    color: #fff;
}

.stat-card {
    background: #fff;
    border-radius: 12px;
    padding: 20px;
    box-shadow: 0 1px 3px rgba(0,0,0,0.1);
    text-align: center;
    margin-bottom: 20px;
}

.stat-card .stat-number {
    font-size: 28px;
    font-weight: 700;
    color: #1e293b;
}

.stat-card .stat-label {
    font-size: 14px;
    color: #64748b;
}

.stat-card .stat-icon {
    font-size: 32px;
    margin-bottom: 10px;
}

.stat-card.text-danger .stat-number { color: #ef4444; }
.stat-card.text-warning .stat-number { color: #f59e0b; }
.stat-card.text-success .stat-number { color: #22c55e; }

.expense-table td {
    vertical-align: middle;
}

.expense-table .badge {
    font-size: 12px;
    padding: 4px 10px;
}

.alert-container {
    margin-bottom: 20px;
}
</style>

<div class="admin-content">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h2><i class="fa-solid fa-arrow-up text-danger me-2"></i> Expenses</h2>
        <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#expenseModal">
            <i class="fa-solid fa-plus"></i> Add Expense
        </button>
    </div>
    
    <!-- Navigation -->
    <div class="account-nav">
        <a href="dashboard.php"><i class="fa-solid fa-chart-pie"></i> Dashboard</a>
        <a href="income.php"><i class="fa-solid fa-arrow-down"></i> Income</a>
        <a href="expenses.php" class="active"><i class="fa-solid fa-arrow-up"></i> Expenses</a>
        <a href="invoices.php"><i class="fa-solid fa-file-invoice"></i> Invoices</a>
        <a href="purchase-orders.php"><i class="fa-solid fa-file-purchase"></i> Purchase Orders</a>
        <a href="vendors.php"><i class="fa-solid fa-building"></i> Vendors</a>
        <a href="po-payments.php"><i class="fa-solid fa-hand-holding-dollar"></i> PO Payments</a>
        <a href="reports.php"><i class="fa-solid fa-chart-bar"></i> Reports</a>
    </div>
    
    <!-- Stats -->
    <div class="row g-4 mb-4">
        <div class="col-lg-4 col-md-6">
            <div class="stat-card">
                <div class="stat-icon text-danger"><i class="fa-solid fa-coins"></i></div>
                <div class="stat-number text-danger"><?php echo number_format($total_expenses); ?> TK</div>
                <div class="stat-label">Total Expenses</div>
            </div>
        </div>
        <div class="col-lg-4 col-md-6">
            <div class="stat-card">
                <div class="stat-icon text-warning"><i class="fa-solid fa-calendar"></i></div>
                <div class="stat-number text-warning"><?php echo number_format($monthly_expenses); ?> TK</div>
                <div class="stat-label">This Month</div>
            </div>
        </div>
        <div class="col-lg-4 col-md-6">
            <div class="stat-card">
                <div class="stat-icon text-success"><i class="fa-solid fa-list"></i></div>
                <div class="stat-number text-success"><?php echo count($expenses); ?></div>
                <div class="stat-label">Total Records</div>
            </div>
        </div>
    </div>
    
    <!-- Alert Container -->
    <div id="alertContainer" class="alert-container"></div>
    
    <?php if ($success_msg): ?>
    <div class="alert alert-success alert-dismissible fade show" role="alert">
        <i class="fa-solid fa-check-circle me-2"></i> <?php echo htmlspecialchars($success_msg); ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
    <?php endif; ?>
    
    <?php if ($error_msg): ?>
    <div class="alert alert-danger alert-dismissible fade show" role="alert">
        <i class="fa-solid fa-exclamation-circle me-2"></i> <?php echo htmlspecialchars($error_msg); ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
    <?php endif; ?>
    
    <!-- Expense List -->
    <div class="card">
        <div class="card-header d-flex justify-content-between align-items-center">
            <h5 class="mb-0">All Expenses</h5>
            <span class="text-muted">Total: <?php echo count($expenses); ?> records</span>
        </div>
        <div class="card-body p-0">
            <div class="table-responsive">
                <table class="table table-hover expense-table mb-0">
                    <thead class="table-light">
                        <tr>
                            <th>Expense No</th>
                            <th>Category</th>
                            <th>Description</th>
                            <th>Vendor</th>
                            <th>Amount</th>
                            <th>Payment Method</th>
                            <th>Date</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody id="expensesTableBody">
                        <?php if (empty($expenses)): ?>
                        <tr>
                            <td colspan="8" class="text-center py-4">
                                <i class="fa-solid fa-inbox fa-2x text-muted d-block mb-2"></i>
                                No expenses found
                            </td>
                        </tr>
                        <?php else: ?>
                        <?php foreach ($expenses as $expense): ?>
                        <tr id="expenseRow_<?php echo $expense['id']; ?>">
                            <td><code><?php echo $expense['expense_no']; ?></code></td>
                            <td>
                                <span class="badge bg-info"><?php echo htmlspecialchars($expense['category']); ?></span>
                            </td>
                            <td><?php echo htmlspecialchars(substr($expense['description'], 0, 30)) . (strlen($expense['description']) > 30 ? '...' : ''); ?></td>
                            <td><?php echo $expense['vendor_name'] ?? '<span class="text-muted">N/A</span>'; ?></td>
                            <td class="text-danger fw-bold"><?php echo number_format($expense['amount']); ?> TK</td>
                            <td>
                                <span class="badge bg-secondary"><?php echo ucfirst($expense['payment_method']); ?></span>
                            </td>
                            <td><?php echo date('d M Y', strtotime($expense['expense_date'])); ?></td>
                            <td>
                                <button onclick="editExpense(<?php echo $expense['id']; ?>)" class="btn btn-sm btn-warning">
                                    <i class="fa-solid fa-edit"></i>
                                </button>
                                <button onclick="deleteExpense(<?php echo $expense['id']; ?>, '<?php echo addslashes($expense['description']); ?>')" class="btn btn-sm btn-danger">
                                    <i class="fa-solid fa-trash"></i>
                                </button>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<!-- Expense Modal -->
<div class="modal fade" id="expenseModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"><i class="fa-solid fa-plus-circle me-2"></i> Add Expense</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST" id="expenseForm">
                <input type="hidden" name="add_expense" value="1">
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label class="form-label">Category <span class="text-danger">*</span></label>
                                <input type="text" name="category" class="form-control" placeholder="e.g. Office Supplies, Utilities, Rent" required>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Description <span class="text-danger">*</span></label>
                                <input type="text" name="description" class="form-control" placeholder="Brief description" required>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Amount <span class="text-danger">*</span></label>
                                <input type="number" name="amount" class="form-control" step="0.01" placeholder="0.00" required>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label class="form-label">Payment Method</label>
                                <select name="payment_method" class="form-control">
                                    <option value="cash">Cash</option>
                                    <option value="bank">Bank Transfer</option>
                                    <option value="bkash">Bkash</option>
                                    <option value="nagad">Nagad</option>
                                    <option value="rocket">Rocket</option>
                                    <option value="card">Card</option>
                                    <option value="other">Other</option>
                                </select>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Vendor (Optional)</label>
                                <select name="vendor_id" class="form-control">
                                    <option value="">Select Vendor</option>
                                    <?php foreach ($vendors as $vendor): ?>
                                    <option value="<?php echo $vendor['id']; ?>"><?php echo htmlspecialchars($vendor['name']); ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Date</label>
                                <input type="date" name="expense_date" class="form-control" value="<?php echo date('Y-m-d'); ?>">
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Reference No</label>
                                <input type="text" name="reference_no" class="form-control" placeholder="Reference number">
                            </div>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Note</label>
                        <textarea name="note" class="form-control" rows="2" placeholder="Additional notes"></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">
                        <i class="fa-solid fa-save"></i> Save Expense
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Edit Expense Modal -->
<div class="modal fade" id="editExpenseModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"><i class="fa-solid fa-edit me-2"></i> Edit Expense</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST" id="editExpenseForm">
                <input type="hidden" name="edit_expense" value="1">
                <input type="hidden" name="expense_id" id="edit_expense_id">
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label class="form-label">Category <span class="text-danger">*</span></label>
                                <input type="text" name="category" id="edit_category" class="form-control" required>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Description <span class="text-danger">*</span></label>
                                <input type="text" name="description" id="edit_description" class="form-control" required>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Amount <span class="text-danger">*</span></label>
                                <input type="number" name="amount" id="edit_amount" class="form-control" step="0.01" required>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label class="form-label">Payment Method</label>
                                <select name="payment_method" id="edit_payment_method" class="form-control">
                                    <option value="cash">Cash</option>
                                    <option value="bank">Bank Transfer</option>
                                    <option value="bkash">Bkash</option>
                                    <option value="nagad">Nagad</option>
                                    <option value="rocket">Rocket</option>
                                    <option value="card">Card</option>
                                    <option value="other">Other</option>
                                </select>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Vendor</label>
                                <select name="vendor_id" id="edit_vendor_id" class="form-control">
                                    <option value="">Select Vendor</option>
                                    <?php foreach ($vendors as $vendor): ?>
                                    <option value="<?php echo $vendor['id']; ?>"><?php echo htmlspecialchars($vendor['name']); ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Date</label>
                                <input type="date" name="expense_date" id="edit_expense_date" class="form-control">
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Reference No</label>
                                <input type="text" name="reference_no" id="edit_reference_no" class="form-control">
                            </div>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Note</label>
                        <textarea name="note" id="edit_note" class="form-control" rows="2"></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">
                        <i class="fa-solid fa-save"></i> Update Expense
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
// ========================================
// DELETE EXPENSE
// ========================================
function deleteExpense(id, description) {
    if (confirm('Are you sure you want to delete expense "' + description + '"?')) {
        var formData = new FormData();
        formData.append('delete_id', id);
        
        fetch('expenses.php', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                var row = document.getElementById('expenseRow_' + id);
                if (row) {
                    row.style.transition = 'all 0.5s ease';
                    row.style.opacity = '0';
                    setTimeout(function() {
                        row.remove();
                        // Update count
                        var count = document.querySelectorAll('#expensesTableBody tr').length - 1;
                        if (count === 0) {
                            document.getElementById('expensesTableBody').innerHTML = `
                                <tr><td colspan="8" class="text-center py-4">
                                    <i class="fa-solid fa-inbox fa-2x text-muted d-block mb-2"></i>
                                    No expenses found
                                </td></tr>
                            `;
                        }
                        // Update stats
                        updateStats();
                    }, 500);
                }
                showAlert('success', 'Expense deleted successfully!');
            } else {
                showAlert('danger', data.message || 'Failed to delete expense');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            showAlert('danger', 'Something went wrong');
        });
    }
}

// ========================================
// UPDATE STATS
// ========================================
function updateStats() {
    var rows = document.querySelectorAll('#expensesTableBody tr');
    var total = 0;
    var count = 0;
    
    rows.forEach(function(row) {
        if (row.querySelector('td[colspan]')) return;
        var amountText = row.querySelector('.text-danger')?.textContent || '';
        var amount = parseFloat(amountText.replace(/[, TK]/g, '')) || 0;
        total += amount;
        count++;
    });
    
    document.querySelector('.stat-card .stat-number.text-danger').textContent = total.toFixed(0) + ' TK';
    document.querySelector('.stat-card .stat-number.text-success').textContent = count;
}

// ========================================
// SHOW ALERT
// ========================================
function showAlert(type, message) {
    var alertContainer = document.getElementById('alertContainer');
    var alertClass = type === 'success' ? 'alert-success' : 'alert-danger';
    var icon = type === 'success' ? 'fa-check-circle' : 'fa-exclamation-circle';
    
    alertContainer.innerHTML = `
        <div class="alert ${alertClass} alert-dismissible fade show" role="alert">
            <i class="fa-solid ${icon} me-2"></i> ${message}
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    `;
    
    setTimeout(function() {
        var alert = alertContainer.querySelector('.alert');
        if (alert) {
            alert.style.transition = 'opacity 0.5s ease';
            alert.style.opacity = '0';
            setTimeout(function() { alert.remove(); }, 500);
        }
    }, 5000);
}

// ========================================
// EDIT EXPENSE - Fetch Data
// ========================================
function editExpense(id) {
    fetch('get-expense.php?id=' + id)
        .then(response => response.json())
        .then(data => {
            if (data) {
                document.getElementById('edit_expense_id').value = data.id;
                document.getElementById('edit_category').value = data.category;
                document.getElementById('edit_description').value = data.description;
                document.getElementById('edit_amount').value = data.amount;
                document.getElementById('edit_payment_method').value = data.payment_method;
                document.getElementById('edit_vendor_id').value = data.vendor_id || '';
                document.getElementById('edit_expense_date').value = data.expense_date;
                document.getElementById('edit_reference_no').value = data.reference_no || '';
                document.getElementById('edit_note').value = data.note || '';
                
                var modal = new bootstrap.Modal(document.getElementById('editExpenseModal'));
                modal.show();
            }
        })
        .catch(error => console.error('Error:', error));
}

// ========================================
// AUTO HIDE ALERTS
// ========================================
document.addEventListener('DOMContentLoaded', function() {
    var alerts = document.querySelectorAll('.alert');
    alerts.forEach(function(alert) {
        setTimeout(function() {
            if (alert) {
                alert.style.transition = 'opacity 0.5s ease';
                alert.style.opacity = '0';
                setTimeout(function() { alert.remove(); }, 500);
            }
        }, 5000);
    });
});
</script>

<?php include '../footer.php'; ?>