<?php
date_default_timezone_set('Asia/Colombo');
include '../config.php';
include '../auth.php';
checkAuth();
// Allow all logged-in users to manage expenses (including cashiers)

// Create expenses table if it doesn't exist
$create_table = "
CREATE TABLE IF NOT EXISTS expenses (
    id INT AUTO_INCREMENT PRIMARY KEY,
    expense_date DATE NOT NULL,
    category VARCHAR(100) NOT NULL,
    description TEXT NOT NULL,
    amount DECIMAL(10,2) NOT NULL,
    payment_method ENUM('cash', 'card', 'bank_transfer') DEFAULT 'cash',
    notes TEXT,
    created_by INT,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (created_by) REFERENCES users(id)
)";
$conn->query($create_table);

// Handle form submission
if ($_POST) {
    $expense_date = $_POST['expense_date'];
    $category = $_POST['category'];
    $description = $_POST['description'];
    $amount = $_POST['amount'];
    $payment_method = $_POST['payment_method'];
    $notes = $_POST['notes'] ?? '';
    
    $stmt = $conn->prepare("INSERT INTO expenses (expense_date, category, description, amount, payment_method, notes, created_by) VALUES (?, ?, ?, ?, ?, ?, ?)");
    $stmt->bind_param("sssdssi", $expense_date, $category, $description, $amount, $payment_method, $notes, $_SESSION['user_id']);
    
    if ($stmt->execute()) {
        $success = "Expense added successfully!";
    } else {
        $error = "Error adding expense: " . $conn->error;
    }
}

// Get recent expenses
$expenses = $conn->query("
    SELECT e.*, u.username 
    FROM expenses e 
    LEFT JOIN users u ON e.created_by = u.id 
    ORDER BY e.expense_date DESC, e.created_at DESC 
    LIMIT 50
")->fetch_all(MYSQLI_ASSOC);
?>
<!DOCTYPE html>
<html>
<head>
    <title>Expenses Management - Textile POS</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
</head>
<body class="bg-light">
    <nav class="navbar navbar-expand-lg navbar-dark bg-primary">
        <div class="container">
            <a class="navbar-brand" href="../dashboard.php">
                <i class="fas fa-cash-register"></i> Textile POS
            </a>
            <div class="navbar-nav ms-auto">
                <a class="nav-link" href="../reports/">Reports</a>
                <a class="nav-link" href="../dashboard.php">Dashboard</a>
            </div>
        </div>
    </nav>

    <div class="container mt-4">
        <div class="row">
            <div class="col-md-4">
                <div class="card">
                    <div class="card-header">
                        <h5><i class="fas fa-plus"></i> Add New Expense</h5>
                    </div>
                    <div class="card-body">
                        <?php if (isset($success)): ?>
                            <div class="alert alert-success"><?= $success ?></div>
                        <?php endif; ?>
                        <?php if (isset($error)): ?>
                            <div class="alert alert-danger"><?= $error ?></div>
                        <?php endif; ?>
                        
                        <form method="POST">
                            <div class="mb-3">
                                <label class="form-label">Date</label>
                                <input type="date" name="expense_date" class="form-control" value="<?= date('Y-m-d') ?>" required>
                            </div>
                            
                            <div class="mb-3">
                                <label class="form-label">Category</label>
                                <select name="category" class="form-select" required>
                                    <option value="">Select Category</option>
                                    <option value="Office Supplies">Office Supplies</option>
                                    <option value="Utilities">Utilities</option>
                                    <option value="Transport">Transport</option>
                                    <option value="Marketing">Marketing</option>
                                    <option value="Rent">Rent</option>
                                    <option value="Equipment">Equipment</option>
                                    <option value="Maintenance">Maintenance</option>
                                    <option value="Professional Services">Professional Services</option>
                                    <option value="Other">Other</option>
                                </select>
                            </div>
                            
                            <div class="mb-3">
                                <label class="form-label">Description</label>
                                <textarea name="description" class="form-control" rows="3" required></textarea>
                            </div>
                            
                            <div class="mb-3">
                                <label class="form-label">Amount (Rs)</label>
                                <input type="number" name="amount" class="form-control" step="0.01" min="0" required>
                            </div>
                            
                            <div class="mb-3">
                                <label class="form-label">Payment Method</label>
                                <select name="payment_method" class="form-select" 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">Notes (Optional)</label>
                                <textarea name="notes" class="form-control" rows="2"></textarea>
                            </div>
                            
                            <button type="submit" class="btn btn-primary w-100">
                                <i class="fas fa-save"></i> Add Expense
                            </button>
                        </form>
                    </div>
                </div>
            </div>
            
            <div class="col-md-8">
                <div class="card">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <h5><i class="fas fa-list"></i> Recent Expenses</h5>
                        <a href="export.php?report_type=expenses&start_date=<?= date('Y-m-01') ?>&end_date=<?= date('Y-m-d') ?>" class="btn btn-success btn-sm">
                            <i class="fas fa-download"></i> Export This Month
                        </a>
                    </div>
                    <div class="card-body">
                        <?php if (empty($expenses)): ?>
                            <div class="text-center text-muted py-4">
                                <i class="fas fa-receipt fa-3x"></i>
                                <p class="mt-2">No expenses recorded yet</p>
                            </div>
                        <?php else: ?>
                            <div class="table-responsive">
                                <table class="table table-striped">
                                    <thead>
                                        <tr>
                                            <th>Date</th>
                                            <th>Category</th>
                                            <th>Description</th>
                                            <th>Amount</th>
                                            <th>Payment</th>
                                            <th>Added By</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($expenses as $expense): ?>
                                        <tr>
                                            <td><?= date('M d, Y', strtotime($expense['expense_date'])) ?></td>
                                            <td>
                                                <span class="badge bg-secondary"><?= htmlspecialchars($expense['category']) ?></span>
                                            </td>
                                            <td>
                                                <?= htmlspecialchars($expense['description']) ?>
                                                <?php if ($expense['notes']): ?>
                                                    <br><small class="text-muted"><?= htmlspecialchars($expense['notes']) ?></small>
                                                <?php endif; ?>
                                            </td>
                                            <td class="text-end">
                                                <strong>Rs <?= number_format($expense['amount'], 2) ?></strong>
                                            </td>
                                            <td>
                                                <span class="badge bg-<?= $expense['payment_method'] == 'cash' ? 'success' : ($expense['payment_method'] == 'card' ? 'primary' : 'info') ?>">
                                                    <?= ucfirst(str_replace('_', ' ', $expense['payment_method'])) ?>
                                                </span>
                                            </td>
                                            <td>
                                                <small><?= htmlspecialchars($expense['username'] ?? 'Unknown') ?></small>
                                            </td>
                                        </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
