<?php
// filename: record_expense.php
session_start();
include 'layouts/dbconn.php';
include 'layouts/session.php';

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

$allowed_roles = ['SUPER_ADMIN', 'HOSPITAL_ADMIN', 'BILLING_CLERK', 'FINANCE_MANAGER'];
if (!in_array($_SESSION['role_code'], $allowed_roles)) {
    header('Location: dashboard.php');
    exit();
}

$user_id = $_SESSION['user_id'];
$message = '';
$error = '';

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $description = trim($_POST['description'] ?? '');
    $expense_date = $_POST['expense_date'] ?? date('Y-m-d');
    $category_id = (int)$_POST['category_id'];
    $amount = (float)$_POST['amount'];
    $cash_account_id = (int)$_POST['cash_account_id']; // Credit cash/bank account
    
    if (empty($description) || $amount <= 0 || $category_id <= 0 || $cash_account_id <= 0) {
        $error = 'Please fill all required fields.';
    } else {
        // Start transaction
        $conn->begin_transaction();
        
        try {
            // Generate journal number (like in upload_reconciliation)
            $today = date('Ymd');
            $max_sql = "SELECT COALESCE(MAX(CAST(SUBSTRING(journal_number, -4) AS UNSIGNED)), 0) + 1 as next_num 
                        FROM journal_entries WHERE journal_number LIKE 'EXP-$today-%'";
            $max_result = $conn->query($max_sql);
            $next_num = $max_result->fetch_assoc()['next_num'];
            $journal_number = 'EXP-' . $today . '-' . str_pad($next_num, 4, '0', STR_PAD_LEFT);
            
            // Insert journal entry (DRAFT initially)
            $journal_sql = "INSERT INTO journal_entries (journal_number, entry_date, entry_type, description, status, created_by, created_at, fiscal_year, fiscal_period) 
                            VALUES (?, ?, 'MANUAL', ?, 'DRAFT', ?, CURRENT_TIMESTAMP, YEAR(?), MONTH(?))";
            $journal_stmt = $conn->prepare($journal_sql);
            $journal_stmt->bind_param('sssisi', $journal_number, $expense_date, $description, $user_id, $expense_date, $expense_date);
            $journal_stmt->execute();
            $journal_id = $conn->insert_id;
            
            // Debit expense account
            $debit_sql = "INSERT INTO journal_entry_lines (journal_id, line_number, account_id, debit_amount, description) VALUES (?, 1, ?, ?, ?)";
            $debit_stmt = $conn->prepare($debit_sql);
            $debit_stmt->bind_param('iids', $journal_id, $category_id, $amount, $description);
            $debit_stmt->execute();
            
            // Credit cash account
            $credit_sql = "INSERT INTO journal_entry_lines (journal_id, line_number, account_id, credit_amount, description) VALUES (?, 2, ?, ?, ?)";
            $credit_stmt = $conn->prepare($credit_sql);
            $credit_stmt->bind_param('iids', $journal_id, $cash_account_id, $amount, $description);
            $credit_stmt->execute();
            
            // Update totals
            $update_sql = "UPDATE journal_entries SET total_debit = ?, total_credit = ? WHERE journal_id = ?";
            $update_stmt = $conn->prepare($update_sql);
            $update_stmt->bind_param('ddi', $amount, $amount, $journal_id);
            $update_stmt->execute();
            
            // Log activity
            $log_sql = "INSERT INTO activity_log (user_id, action, module, record_id, record_type, new_values) VALUES (?, 'CREATE', 'EXPENSE', ?, 'JOURNAL_ENTRY', ?)";
            $log_values = json_encode(['number' => $journal_number, 'amount' => $amount, 'category' => $category_id]);
            $log_stmt = $conn->prepare($log_sql);
            $log_stmt->bind_param('iis', $user_id, $journal_id, $log_values);
            $log_stmt->execute();
            
            $conn->commit();
            
            // Notification: Email finance
            // $mail = new PHPMailer(true); $mail->Subject = 'New Expense Recorded'; $mail->send();
            
            $message = 'Expense recorded successfully! Journal: ' . $journal_number;
            
            // Optional: SMS via AfricasTalking
            // $sms = new AfricasTalking\SDK(); $sms->sms()->send(['to' => '+2547xx', 'message' => "New expense KES $amount - $description"]);
            
        } catch (Exception $e) {
            $conn->rollback();
            $error = 'Failed to record expense: ' . $e->getMessage();
        }
    }
}

// Fetch expense categories (chart_of_accounts where account_type = 'EXPENSE')
$cat_sql = "SELECT account_id, account_code, account_name FROM chart_of_accounts WHERE account_type = 'EXPENSE' AND is_active = 1 ORDER BY account_name";
$cat_result = $conn->query($cat_sql);

// Fetch cash accounts (ASSET with 'cash' in name)
$cash_sql = "SELECT account_id, account_name FROM chart_of_accounts WHERE account_type = 'ASSET' AND (account_name LIKE '%cash%' OR account_name LIKE '%petty%') AND is_active = 1 ORDER BY account_name";
$cash_result = $conn->query($cash_sql);
?>

<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Record Expense')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet">
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <div class="row">
                        <div class="col-12">
                            <div class="page-title-box d-sm-flex align-items-center justify-content-between">
                                <h4 class="mb-sm-0">Record Expense</h4>
                                <div class="page-title-right">
                                    <ol class="breadcrumb m-0">
                                        <li class="breadcrumb-item"><a href="dashboard.php">Dashboard</a></li>
                                        <li class="breadcrumb-item"><a href="list_expenses.php">Expenses</a></li>
                                        <li class="breadcrumb-item active">Record</li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-lg-8 mx-auto">
                            <div class="card expense-card">
                                <div class="card-header expense-header">
                                    <h5 class="mb-0 text-white"><i class="ri-add-circle-line me-2"></i>Record New Expense</h5>
                                </div>
                                <div class="card-body">
                                    <?php if ($message): ?>
                                    <div class="alert alert-success alert-dismissible fade show" role="alert">
                                        <?php echo htmlspecialchars($message); ?>
                                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                                    </div>
                                    <?php endif; ?>
                                    
                                    <?php if ($error): ?>
                                    <div class="alert alert-danger alert-dismissible fade show" role="alert">
                                        <?php echo htmlspecialchars($error); ?>
                                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                                    </div>
                                    <?php endif; ?>
                                    
                                    <form method="POST">
                                        <div class="mb-3">
                                            <label class="form-label">Date <span class="text-danger">*</span></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">Description <span class="text-danger">*</span></label>
                                            <textarea class="form-control" name="description" rows="2" placeholder="e.g., Office supplies for ENT clinic" required><?php echo htmlspecialchars($description ?? ''); ?></textarea>
                                        </div>
                                        
                                        <div class="row">
                                            <div class="col-md-6 mb-3">
                                                <label class="form-label">Expense Category <span class="text-danger">*</span></label>
                                                <select class="form-select" name="category_id" required>
                                                    <option value="">Select Category</option>
                                                    <?php while ($cat = $cat_result->fetch_assoc()): ?>
                                                    <option value="<?php echo $cat['account_id']; ?>"><?php echo htmlspecialchars($cat['account_code'] . ' - ' . $cat['account_name']); ?></option>
                                                    <?php endwhile; ?>
                                                </select>
                                            </div>
                                            <div class="col-md-6 mb-3">
                                                <label class="form-label">Amount (KES) <span class="text-danger">*</span></label>
                                                <input type="number" step="0.01" class="form-control" name="amount" placeholder="0.00" required>
                                            </div>
                                        </div>
                                        
                                        <div class="mb-3">
                                            <label class="form-label">Paid From (Cash/Bank Account) <span class="text-danger">*</span></label>
                                            <select class="form-select" name="cash_account_id" required>
                                                <option value="">Select Account</option>
                                                <?php while ($cash = $cash_result->fetch_assoc()): ?>
                                                <option value="<?php echo $cash['account_id']; ?>"><?php echo htmlspecialchars($cash['account_name']); ?></option>
                                                <?php endwhile; ?>
                                            </select>
                                        </div>
                                        
                                        <div class="d-flex gap-2">
                                            <button type="submit" class="btn btn-primary">
                                                <i class="ri-save-line me-1"></i>Record Expense
                                            </button>
                                            <a href="list_expenses.php" class="btn btn-secondary">
                                                <i class="ri-arrow-left-line me-1"></i>Back to List
                                            </a>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>
    <script src="assets/js/app.js"></script>
</body>
</html>