<?php
error_reporting(E_ALL);
ini_set('display_errors', 0);

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

if (!isset($_SESSION['user_id'])) {
    header('Location: index.php');
    exit;
}

// Role-based access control
$allowed_roles = ['admin', 'accountant', 'cashier']; // Adjust per page

if (!in_array($_SESSION['role'], $allowed_roles)) {
    header('Location: dashboard.php?error=access_denied');
    exit;
}

require_once 'config.php';
$conn = getDBConnection();

// Handle POST form submissions
$message = '';
$messageType = '';

// Add Expense
if (isset($_POST['action']) && $_POST['action'] === 'add') {
    $expense_date   = trim((string) ($_POST['expense_date']   ?? ''));
    $category       = trim((string) ($_POST['category']       ?? ''));
    $description    = trim((string) ($_POST['description']    ?? ''));
    $amount         = floatval($_POST['amount'] ?? 0);
    $payment_method = trim((string) ($_POST['payment_method'] ?? 'cash'));
    $vendor         = trim((string) ($_POST['vendor']         ?? ''));

    if (empty($expense_date) || empty($category) || empty($description) || $amount <= 0) {
        $message = 'Please fill all required fields';
        $messageType = 'danger';
    } else {
        $stmt = $conn->prepare("INSERT INTO expenses (expense_date, category, description, amount, payment_method, vendor) VALUES (?, ?, ?, ?, ?, ?)");
        $stmt->bind_param("sssdss", $expense_date, $category, $description, $amount, $payment_method, $vendor);

        if ($stmt->execute()) {
              //$phonss = '0540885509';
               // Get school number from settings
                $school_name = getSetting('school_name', 'Our School');
                $phonss = getSetting('school_phone', '0537793106');
               //  $phoness = '0594453744';

            $message = 'Expense added successfully!';
            $formatted_amount = formatCurrency($amount);
             $sms_message = "Dear Principal, An expense of {$formatted_amount} has been recorded under the {$category} category. Please check the system for more details. Thank you - {$school_name}";
               
              
                // Send SMS to principal
                
                   // sendSMS($phoness, $sms_message);
                    sendSMS($phonss, $sms_message);
               
            $messageType = 'success';
        } else {
            $message = 'Failed to add expense: ' . $stmt->error;
            $messageType = 'danger';
        }
        $stmt->close();
    }
}

// Delete Expense (via GET for simplicity)
if (isset($_GET['action']) && $_GET['action'] === 'delete' && isset($_GET['id'])) {
    $id = intval($_GET['id']);
    
    $stmt = $conn->prepare("DELETE FROM expenses WHERE id = ?");
    $stmt->bind_param("i", $id);

    if ($stmt->execute()) {
        $message = 'Expense deleted successfully!';
        $messageType = 'success';
    } else {
        $message = 'Failed to delete expense: ' . $stmt->error;
        $messageType = 'danger';
    }
    $stmt->close();
}

// Helper function to get setting value
function getSetting($key, $default = '') {
    global $conn;
    $result = $conn->query("SELECT setting_value FROM settings WHERE setting_key = '$key'");
    if ($result && $row = $result->fetch_assoc()) {
        return $row['setting_value'];
    }
    return $default;
}

// Get all expenses
$expenses = [];
$result = $conn->query("SELECT * FROM expenses ORDER BY expense_date DESC");
if ($result) {
    while ($row = $result->fetch_assoc()) {
        $expenses[] = $row;
    }
}

// Get total expenses
$totalExpenses = 0;
$result = $conn->query("SELECT COALESCE(SUM(amount), 0) as total FROM expenses");
if ($result) {
    $row = $result->fetch_assoc();
    $totalExpenses = $row['total'];
}

// Get expenses by category
$categoryTotals = [];
$result = $conn->query("SELECT category, SUM(amount) as total FROM expenses GROUP BY category");
if ($result) {
    while ($row = $result->fetch_assoc()) {
        $categoryTotals[$row['category']] = $row['total'];
    }
}

// Finance & Procurement add-on: receipt counts per expense (feature 3).
$financeSuite   = function_exists('hasModule') && hasModule('finance_suite');
$receiptCounts  = [];
if ($financeSuite) {
    $rc = $conn->query("SELECT expense_id, COUNT(*) c FROM expense_attachments WHERE expense_id IS NOT NULL GROUP BY expense_id");
    if ($rc) while ($row = $rc->fetch_assoc()) $receiptCounts[(int) $row['expense_id']] = (int) $row['c'];
}
$finance_base = defined('BASE_URL') ? rtrim(BASE_URL, '/') : '';

$conn->close();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Expenses - EduTrack Pro</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link rel="stylesheet" href="css/style.css">
    <link rel="stylesheet" href="https://cdn.datatables.net/1.13.6/css/dataTables.bootstrap5.min.css">
<link rel="stylesheet" href="https://cdn.datatables.net/buttons/2.4.1/css/buttons.bootstrap5.min.css">
</head>
<body>
    <div class="wrapper">
        <!-- Sidebar -->
        <nav id="sidebar" class="sidebar">
        <?php echo buildSidebar(basename($_SERVER['PHP_SELF'])); ?>
        </nav>

        <!-- Main Content -->
        <div class="main-content">
            <!-- Header -->
            <header class="header">
                <button class="btn-toggle" id="sidebarToggle">
                    <i class="fas fa-bars"></i>
                </button>
                <div class="header-right">
                    <div class="dropdown">
                        <button class="btn btn-link dropdown-toggle" type="button" data-bs-toggle="dropdown">
                            <i class="fas fa-user-circle me-2"></i><?php echo htmlspecialchars((string) ($_SESSION['full_name'] ?? '')); ?>
                        </button>
                        <ul class="dropdown-menu dropdown-menu-end">
                            <li><a class="dropdown-item" href="settings.php"><i class="fas fa-cog me-2"></i>Settings</a></li>
                            <li><hr class="dropdown-divider"></li>
                            <li><a class="dropdown-item" href="logout.php"><i class="fas fa-sign-out-alt me-2"></i>Logout</a></li>
                        </ul>
                    </div>
                </div>
            </header>

            <!-- Page Content -->
            <main class="content">
                <div class="content-header">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <h2><i class="fas fa-file-invoice-dollar me-2"></i>Expense Management</h2>
                            <p>Track and manage all school expenses</p>
                        </div>
                        <div class="d-flex gap-2">
                            <?php if ($financeSuite): ?>
                            <a href="<?php echo $finance_base; ?>/finance/index.php" class="btn btn-outline-success">
                                <i class="fas fa-sack-dollar me-2"></i>Procurement &amp; Approvals
                            </a>
                            <?php endif; ?>
                            <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addExpenseModal">
                                <i class="fas fa-plus me-2"></i>Add Expense
                            </button>
                        </div>
                    </div>
                </div>

                <!-- Alert Message -->
                <?php if ($message): ?>
                <div class="alert alert-<?php echo $messageType; ?> alert-dismissible fade show" role="alert">
                    <?php echo $message; ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
                <?php endif; ?>

                <!-- Stats Cards -->
                <div class="row mb-4">
                    <div class="col-md-4">
                        <div class="stat-card stat-danger">
                            <div class="stat-icon">
                                <i class="fas fa-wallet"></i>
                            </div>
                            <div class="stat-info">
                                <h3><?php echo formatCurrency($totalExpenses); ?></h3>
                                <p>Total Expenses</p>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="stat-card stat-warning">
                            <div class="stat-icon">
                                <i class="fas fa-receipt"></i>
                            </div>
                            <div class="stat-info">
                                <h3><?php echo count($expenses); ?></h3>
                                <p>Total Transactions</p>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="stat-card stat-primary">
                            <div class="stat-icon">
                                <i class="fas fa-chart-pie"></i>
                            </div>
                            <div class="stat-info">
                                <h3><?php echo count($categoryTotals); ?></h3>
                                <p>Categories</p>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Category Breakdown -->
                <div class="row mb-4">
                    <div class="col-12">
                        <div class="card">
                            <div class="card-header">
                                <h5><i class="fas fa-chart-pie me-2"></i>Expenses by Category</h5>
                            </div>
                            <div class="card-body">
                                <div class="row">
                                    <?php if (empty($categoryTotals)): ?>
                                        <div class="col-12 text-center text-muted py-3">No expenses recorded yet</div>
                                    <?php else: ?>
                                        <?php foreach ($categoryTotals as $category => $total): ?>
                                            <div class="col-md-3">
                                                <div class="text-center p-3">
                                                    <h4 class="text-danger"><?php echo formatCurrency($total); ?></h4>
                                                    <p class="text-muted"><?php echo htmlspecialchars($category); ?></p>
                                                </div>
                                            </div>
                                        <?php endforeach; ?>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Expenses Table -->
                <div class="card">
                    <div class="card-header">
                        <div class="d-flex justify-content-between align-items-center">
                            <h5><i class="fas fa-list me-2"></i>All Expenses</h5>
                            <div class="search-box" style="display:none">
                                <i class="fas fa-search"></i>
                                <input type="text" class="form-control" id="searchInput" placeholder="Search expenses...">
                            </div>
                        </div>
                    </div>
                    <div class="card-body">
                        <div class="table-responsive">
                            <table class="table table-hover" id='expensesTable'>
                                <thead>
                                    <tr>
                                        <th>Date</th>
                                        <th>Category</th>
                                        <th>Description</th>
                                        <th>Amount</th>
                                        <th>Payment Method</th>
                                        <th>Vendor</th>
                                        <?php if ($financeSuite): ?><th>Receipts</th><?php endif; ?>
                                        <th>Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php if (empty($expenses)): ?>
                                        <tr>
                                            <td colspan="<?php echo $financeSuite ? 8 : 7; ?>" class="text-center py-5">
                                                <div class="empty-state">
                                                    <i class="fas fa-file-invoice-dollar"></i>
                                                    <h4>No Expenses</h4>
                                                    <p>Add your first expense to start tracking</p>
                                                </div>
                                            </td>
                                        </tr>
                                    <?php else: ?>
                                        <?php foreach ($expenses as $expense): ?>
                                            <tr>
                                                <td><?php echo date('d M Y', strtotime($expense['expense_date'])); ?></td>
                                                <td><span class="badge badge-primary"><?php echo htmlspecialchars($expense['category']); ?></span></td>
                                                <td><?php echo htmlspecialchars($expense['description']); ?></td>
                                                <td><?php echo formatCurrency($expense['amount']); ?></td>
                                                <td><?php echo ucfirst($expense['payment_method']); ?></td>
                                                <td><?php echo htmlspecialchars($expense['vendor'] ?: '-'); ?></td>
                                                <?php if ($financeSuite): $rcCount = $receiptCounts[(int) $expense['id']] ?? 0; ?>
                                                <td>
                                                    <button type="button" class="btn btn-sm btn-outline-secondary" onclick="openReceipts(<?php echo (int) $expense['id']; ?>)">
                                                        <i class="fas fa-paperclip"></i>
                                                        <?php if ($rcCount): ?><span class="badge bg-success"><?php echo $rcCount; ?></span><?php endif; ?>
                                                    </button>
                                                </td>
                                                <?php endif; ?>
                                                <td>
                                                    <div class="action-buttons">
                                                        <a href="expenses.php?action=delete&id=<?php echo $expense['id']; ?>" class="action-btn delete" title="Delete" onclick="return confirm('Are you sure you want to delete this expense?');">
                                                            <i class="fas fa-trash"></i>
                                                        </a>
                                                    </div>
                                                </td>
                                            </tr>
                                        <?php endforeach; ?>
                                    <?php endif; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </main>

            <!-- Footer -->
            <footer class="footer">
                <p>&copy; 2024 EduTrack Pro. All rights reserved.</p>
            </footer>
        </div>
    </div>

    <!-- Add Expense Modal -->
    <div class="modal fade" id="addExpenseModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"><i class="fas fa-plus-circle me-2"></i>Add Expense</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST" action="expenses.php">
                <input type="hidden" name="action" value="add">
                <div class="modal-body">
                        <div class="mb-3">
                            <label class="form-label">Expense Date *</label>
                            <input type="date" class="form-control" name="expense_date" value="<?php echo date('Y-m-d'); ?>" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Category *</label>
                            <select class="form-select" name="category" required>
                                <option value="">Select Category</option>
                                <option value="Salaries">Salaries</option>
                                <option value="Utilities">Utilities</option>
                                <option value="Supplies">Supplies</option>
                                <option value="Maintenance">Maintenance</option>
                                <option value="Transport">Transport</option>
                                <option value="Events">Events</option>
                                <option value="Other">Other</option>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Description *</label>
                            <textarea class="form-control" name="description" rows="2" placeholder="Enter expense description" required></textarea>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Amount *</label>
                            <input type="number" class="form-control" name="amount" placeholder="Enter amount" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Payment Method *</label>
                            <select class="form-select" name="payment_method" required>
                                <option value="cash">Cash</option>
                                <option value="card">Card</option>
                                <option value="bank_transfer">Bank Transfer</option>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Vendor (Optional)</label>
                            <input type="text" class="form-control" name="vendor" placeholder="Enter vendor name">
                        </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">Add Expense</button>
                </div>
            </form>
        </div>
    </div>
</div>

<?php if ($financeSuite): ?>
<!-- Receipts modal (Finance & Procurement add-on) -->
<div class="modal fade" id="receiptsModal" tabindex="-1"><div class="modal-dialog"><div class="modal-content">
    <div class="modal-header"><h5 class="modal-title"><i class="fas fa-paperclip me-2"></i>Expense Receipts</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
    <div class="modal-body">
        <div id="receiptsList" class="mb-3">Loading…</div>
        <div class="input-group">
            <input type="file" id="receiptFile" class="form-control" accept="image/*,application/pdf">
            <button class="btn btn-success" id="receiptUploadBtn"><i class="fas fa-upload me-1"></i>Attach</button>
        </div>
    </div>
</div></div></div>
<script>
const FIN_BASE="<?php echo $finance_base; ?>";
let curExpenseId=null;
function fEsc(s){const d=document.createElement('div');d.textContent=s==null?'':s;return d.innerHTML;}
function openReceipts(id){
    curExpenseId=id;
    new bootstrap.Modal(document.getElementById('receiptsModal')).show();
    loadReceipts();
}
function loadReceipts(){
    fetch(`${FIN_BASE}/finance/ajax/receipts.php?action=list&expense_id=${curExpenseId}`).then(r=>r.json()).then(d=>{
        const el=document.getElementById('receiptsList');
        if(!d.success){el.innerHTML='<div class="text-danger">'+fEsc(d.message)+'</div>';return;}
        if(!d.data.length){el.innerHTML='<p class="text-muted small mb-0">No receipts attached yet.</p>';return;}
        el.innerHTML='<div class="d-flex flex-wrap gap-2">'+d.data.map(a=>{
            const url=FIN_BASE+'/'+a.file_path, isImg=(a.mime||'').startsWith('image/');
            return `<a href="${url}" target="_blank" class="text-center" style="width:90px">
              ${isImg?`<img src="${url}" style="width:90px;height:68px;object-fit:cover;border-radius:8px;border:1px solid #ddd">`
                     :`<div style="width:90px;height:68px;border:1px solid #ddd;border-radius:8px;display:flex;align-items:center;justify-content:center;background:#f8f9fa"><i class="fas fa-file-pdf fa-2x text-danger"></i></div>`}
              <div class="small text-truncate" style="width:90px">${fEsc(a.original_name||'')}</div></a>`;
        }).join('')+'</div>';
    });
}
document.getElementById('receiptUploadBtn').addEventListener('click',function(){
    const f=document.getElementById('receiptFile').files[0];
    if(!f){alert('Choose a file first.');return;}
    const fd=new FormData();fd.append('action','upload');fd.append('expense_id',curExpenseId);fd.append('receipt',f);
    this.disabled=true;
    fetch(`${FIN_BASE}/finance/ajax/receipts.php`,{method:'POST',body:fd}).then(r=>r.json()).then(d=>{
        this.disabled=false;
        if(d.success){document.getElementById('receiptFile').value='';loadReceipts();}else alert(d.message);
    }).catch(()=>{this.disabled=false;alert('Upload failed.');});
});
</script>
<?php endif; ?>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://code.jquery.com/jquery-3.7.0.min.js"></script>
    <script src="js/main.js"></script>
    <script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.13.6/js/dataTables.bootstrap5.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.1/js/dataTables.buttons.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.1/js/buttons.bootstrap5.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.1/js/buttons.html5.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.1/js/buttons.print.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js"></script>

<script>
    $(document).ready(function() {
        $('#expensesTable').DataTable({
            pageLength: 25,
            lengthMenu: [[10, 25, 50, 100, -1], [10, 25, 50, 100, "All"]],
            order: [[0, 'desc']],
            dom: 'Bfrtip',
            buttons: [
                {
                    extend: 'excel',
                    text: '<i class="fas fa-file-excel me-2"></i>Export to Excel',
                    className: 'btn btn-success btn-sm',
                    exportOptions: {
                        columns: [0, 1, 2, 3, 4, 5]
                    }
                },
                {
                    extend: 'pdf',
                    text: '<i class="fas fa-file-pdf me-2"></i>Export to PDF',
                    className: 'btn btn-danger btn-sm',
                    exportOptions: {
                        columns: [0, 1, 2, 3, 4, 5]
                    }
                },
                {
                    extend: 'print',
                    text: '<i class="fas fa-print me-2"></i>Print',
                    className: 'btn btn-info btn-sm'
                }
            ],
            language: {
                emptyTable: "No expenses found"
            }
        });
    });
</script>
</body>
</html>
