<?php
require_once __DIR__ . '/../library/auth.php';
require_once __DIR__ . '/../library/audit_log.php';  
$current_session_id = get_current_session_id($pdo);
$school_id = $_SESSION['school_id'];
allow_roles(['admin', 'accountant']);

// ======================================================
// ADD EXPENSE
// ======================================================

if (isset($_POST['save_expense'])) {

    $category_id  = intval($_POST['category_id']);
    $description  = trim($_POST['description']);
    $amount       = floatval($_POST['amount']);
    $payment_mode = trim($_POST['payment_mode']);
    $payment_date = $_POST['payment_date'];

    // Validate Category
    $check_category = $pdo->prepare("
        SELECT id 
        FROM expense_categories 
        WHERE id = ? AND school_id = ?
    ");

    $check_category->execute([
        $category_id,
        $school_id
    ]);

    if ($check_category->rowCount() == 0) {

        header("Location: add_expense.php?msg=❌ Invalid Category!");
        exit;
    }

    // Validate Amount
    if ($amount <= 0) {

        header("Location: add_expense.php?msg=❌ Invalid Amount!");
        exit;
    }

    // Receipt Number
    $receipt_no = 'EXP-' . date('YmdHis') . rand(100,999);

    // Insert Expense
    $stmt = $pdo->prepare("
        INSERT INTO expenses
        (
            school_id,
			session_id,
            category_id,
            description,
            amount,
            payment_mode,
            payment_date,
            receipt_no
        )
        VALUES
        (
            ?, ?, ?, ?, ?, ?, ?, ?
        )
    ");

    $stmt->execute([
        $school_id,
		$current_session_id,
        $category_id,
        $description,
        $amount,
        $payment_mode,
        $payment_date,
        $receipt_no
    ]);

    // Audit Log
    logActivity($pdo, [
        'school_id' => $school_id,
        'user_id'   => $_SESSION['user_id'],
        'module'    => 'Expenses',
        'action'    => 'CREATE',
        'record_id' => $pdo->lastInsertId(),
        'message'   => "Expense added: {$description} (₹{$amount})",
        'old_data'  => null,
        'new_data'  => [
            'category_id'  => $category_id,
            'description'  => $description,
            'amount'       => $amount,
            'payment_mode' => $payment_mode,
            'payment_date' => $payment_date,
            'receipt_no'   => $receipt_no
        ]
    ]);

    header("Location: add_expense.php?msg=✅ Expense Added Successfully!");
    exit;
}

// ======================================================
// UPDATE EXPENSE
// ======================================================

if (isset($_POST['update_expense'])) {

    $expense_id    = intval($_POST['expense_id']);
    $category_id   = intval($_POST['category_id']);
    $description   = trim($_POST['description']);
    $amount        = floatval($_POST['amount']);
    $payment_mode  = trim($_POST['payment_mode']);
    $payment_date  = $_POST['payment_date'];

    // Validate Expense
    $check_expense = $pdo->prepare("
        SELECT id
        FROM expenses
        WHERE id = ?
AND school_id = ?
AND session_id = ?
    ");

    $check_expense->execute([
        $expense_id,
        $school_id,
		$current_session_id
    ]);

    if ($check_expense->rowCount() == 0) {

        header("Location: view_expense.php?msg=❌ Expense Not Found!");
        exit;
    }

    // Validate Category
    $check_category = $pdo->prepare("
        SELECT id
        FROM expense_categories
        WHERE id = ? AND school_id = ?
    ");

    $check_category->execute([
        $category_id,
        $school_id,
		
    ]);

    if ($check_category->rowCount() == 0) {

        header("Location: view_expense.php?msg=❌ Invalid Category!");
        exit;
    }

    // Validate Amount
    if ($amount <= 0) {

        header("Location: view_expense.php?msg=❌ Invalid Amount!");
        exit;
    }

    // Get Old Data (Before Update)
    $old_stmt = $pdo->prepare("SELECT * FROM expenses WHERE id = ? AND school_id = ?");
    $old_stmt->execute([$expense_id, $school_id]);
    $old_data = $old_stmt->fetch(PDO::FETCH_ASSOC);

    // Update Query
    $stmt = $pdo->prepare("
        UPDATE expenses
        SET
            category_id = ?,
            description = ?,
            amount = ?,
            payment_mode = ?,
            payment_date = ?
        WHERE id = ? AND school_id = ?
    ");

    $stmt->execute([
        $category_id,
        $description,
        $amount,
        $payment_mode,
        $payment_date,
        $expense_id,
        $school_id
    ]);

    // Audit Log
    logActivity($pdo, [
        'school_id' => $school_id,
        'user_id'   => $_SESSION['user_id'],
        'module'    => 'Expenses',
        'action'    => 'UPDATE',
        'record_id' => $expense_id,
        'message'   => "Expense updated: {$description} (₹{$amount})",
        'old_data'  => $old_data,
        'new_data'  => [
            'category_id'  => $category_id,
            'description'  => $description,
            'amount'       => $amount,
            'payment_mode' => $payment_mode,
            'payment_date' => $payment_date
        ]
    ]);

    header("Location: view_expense.php?msg=🔄 Expense Updated Successfully!");
    exit;
}

// ======================================================
// DELETE EXPENSE
// ======================================================

if (isset($_GET['delete'])) {

    $expense_id = intval($_GET['delete']);

    // Validate Expense
    $check = $pdo->prepare("
        SELECT id
        FROM expenses
        WHERE id = ? AND school_id = ?
    ");

    $check->execute([
        $expense_id,
        $school_id
    ]);

    if ($check->rowCount() == 0) {

        header("Location: view_expense.php?msg=❌ Expense Not Found!");
        exit;
    }

    // Get Old Data Before Delete
    $old_stmt = $pdo->prepare("SELECT * FROM expenses WHERE id = ? AND school_id = ?");
    $old_stmt->execute([$expense_id, $school_id]);
    $old_data = $old_stmt->fetch(PDO::FETCH_ASSOC);

    // Audit Log
    logActivity($pdo, [
        'school_id' => $school_id,
        'user_id'   => $_SESSION['user_id'],
        'module'    => 'Expenses',
        'action'    => 'DELETE',
        'record_id' => $expense_id,
        'message'   => "Expense deleted: Receipt #{$old_data['receipt_no']}",
        'old_data'  => $old_data,
        'new_data'  => null
    ]);

    // Delete Query
    $stmt = $pdo->prepare("
        DELETE FROM expenses
        WHERE id = ? AND school_id = ?
    ");

    $stmt->execute([
        $expense_id,
        $school_id
    ]);

    header("Location: view_expense.php?msg=🗑️ Expense Deleted Successfully!");
    exit;
}

?>