<?php

require_once __DIR__ . '/../library/auth.php';
require_once __DIR__ . '/../library/audit_log.php';

$school_id = $_SESSION['school_id'];
$current_session_id = get_current_session_id($pdo);
allow_roles(['admin', 'accountant']);

// ======================================================
// ACTION ROUTER
// ======================================================

$action = $_POST['action'] ?? $_GET['action'] ?? '';

switch ($action) {

    case 'add':
        addIncome();
        break;

    case 'edit':
        updateIncome();
        break;

    case 'delete':
        deleteIncome();
        break;

    default:
        header("Location: view_income.php");
        exit;
}

// ======================================================
// ADD INCOME
// ======================================================

function addIncome()
{
    global $pdo, $school_id, $current_session_id;

    try {

        $category_id  = trim($_POST['category_id'] ?? '');

        $description  = trim($_POST['description'] ?? '');

        $amount       = (float)($_POST['amount'] ?? 0);

        $payment_mode = trim($_POST['payment_mode'] ?? '');

        $payment_date = trim($_POST['payment_date'] ?? '');

        // ==================================================
        // VALIDATION
        // ==================================================

        if (
            $category_id === '' ||
            $description === '' ||
            $amount <= 0 ||
            $payment_mode === '' ||
            $payment_date === ''
        ) {

            header("Location: add.php?msg=Please fill all required fields");

            exit;
        }

        // ==================================================
        // SIMPLE RECEIPT NUMBER
        // ==================================================

        $receipt_no =
            'INC-'
            .
            time();

        // ==================================================
        // INSERT INCOME
        // ==================================================

        $stmt = $pdo->prepare("
            INSERT INTO income
            (
                school_id,
				session_id,
                category_id,
                description,
                amount,
                payment_mode,
                payment_date,
                receipt_no,
                created_at
            )

            VALUES
            (
                ?, ?, ?, ?, ?, ?, ?, ?, NOW()
            )
        ");

        $stmt->execute([

            $school_id,
			$current_session_id,

            $category_id,

            $description,

            $amount,

            $payment_mode,

            $payment_date,

            $receipt_no

        ]);

        // ==================================================
        // LAST INSERT ID
        // ==================================================

        $income_id = $pdo->lastInsertId();

        // ==================================================
        // AUDIT LOG
        // ==================================================

        logActivity($pdo, [

            'school_id' => $school_id,

            'user_id' => $_SESSION['user_id'],

            'module' => 'Income',

            'action' => 'CREATE',

            'record_id' => $income_id,

            'message' => "Income added: {$description}",

            '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.php?msg=Income added successfully");

        exit;

    } catch (Exception $e) {

        header(
            "Location: add.php?msg="
            . urlencode($e->getMessage())
        );

        exit;
    }
}

// ======================================================
// UPDATE INCOME
// ======================================================

function updateIncome()
{
    global $pdo, $school_id, $current_session_id;

    try {

        $id            = (int)($_POST['income_id'] ?? 0);

        $category_id   = trim($_POST['category_id'] ?? '');

        $description   = trim($_POST['description'] ?? '');

        $amount        = (float)($_POST['amount'] ?? 0);

        $payment_mode  = trim($_POST['payment_mode'] ?? '');

        $payment_date  = trim($_POST['payment_date'] ?? '');

        // ==================================================
        // VALIDATION
        // ==================================================

        if (
            $id <= 0 ||
            $category_id === '' ||
            $description === '' ||
            $amount <= 0
        ) {

            header("Location: view_income.php?msg=Invalid input");

            exit;
        }

        // ==================================================
        // OLD DATA
        // ==================================================

        $old_stmt = $pdo->prepare("
            SELECT *
            FROM income
            WHERE id = ?
            AND school_id = ?
			AND session_id = ?
        ");

        $old_stmt->execute([
    $id,
    $school_id,
    $current_session_id
]);

        $old_data = $old_stmt->fetch(PDO::FETCH_ASSOC);

        if (!$old_data) {

            header("Location: view_income.php?msg=Income not found");

            exit;
        }

        // ==================================================
        // UPDATE QUERY
        // ==================================================

        $stmt = $pdo->prepare("
            UPDATE income

            SET

                category_id = ?,
                description = ?,
                amount = ?,
                payment_mode = ?,
                payment_date = ?

            WHERE id = ?
            AND school_id = ?
			AND session_id = ?
        ");

        $stmt->execute([

            $category_id,

            $description,

            $amount,

            $payment_mode,

            $payment_date,

            $id,

            $school_id,
			$current_session_id

        ]);

        // ==================================================
        // AUDIT LOG
        // ==================================================

        logActivity($pdo, [

            'school_id' => $school_id,

            'user_id' => $_SESSION['user_id'],

            'module' => 'Income',

            'action' => 'UPDATE',

            'record_id' => $id,

            'message' => "Income updated: {$description}",

            '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_income.php?msg=Income updated successfully");

        exit;

    } catch (Exception $e) {

        header(
            "Location: view_income.php?msg="
            . urlencode($e->getMessage())
        );

        exit;
    }
}

// ======================================================
// DELETE INCOME
// ======================================================

function deleteIncome()
{
    global $pdo, $school_id, $current_session_id;

    try {

        $id = (int)($_GET['id'] ?? $_POST['income_id'] ?? 0);

        if ($id <= 0) {

            header("Location: view_income.php?msg=Invalid income id");

            exit;
        }

        // ==================================================
        // OLD DATA
        // ==================================================

        $old_stmt = $pdo->prepare("
            SELECT *
            FROM income
            WHERE id = ?
            AND school_id = ?
			AND session_id = ?
        ");

        $old_stmt->execute([
            $id,
            $school_id,
			$current_session_id
        ]);

        $old_data = $old_stmt->fetch(PDO::FETCH_ASSOC);

        if (!$old_data) {

            header("Location: view_income.php?msg=Income not found");

            exit;
        }

        // ==================================================
        // DELETE QUERY
        // ==================================================

        $stmt = $pdo->prepare("
            DELETE FROM income
            WHERE id = ?
            AND school_id = ?
			AND session_id = ?
        ");

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

        // ==================================================
        // AUDIT LOG
        // ==================================================

        logActivity($pdo, [

            'school_id' => $school_id,

            'user_id' => $_SESSION['user_id'],

            'module' => 'Income',

            'action' => 'DELETE',

            'record_id' => $id,

            'message' => 'Income deleted',

            'old_data' => $old_data

        ]);

        header("Location: view_income.php?msg=Income deleted successfully");

        exit;

    } catch (Exception $e) {

        header(
            "Location: view_income.php?msg="
            . urlencode($e->getMessage())
        );

        exit;
    }
}
?>