<?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']);


// ======================================================
// GET / CREATE SALARY CATEGORY
// ======================================================

$salary_category = $pdo->prepare("

    SELECT
        id

    FROM expense_categories

    WHERE school_id = ?
    AND name = 'Salary'

    LIMIT 1

");

$salary_category->execute([$school_id]);

$salary_category_id = $salary_category->fetchColumn();


// ======================================================
// CREATE CATEGORY IF NOT EXISTS
// ======================================================

if (!$salary_category_id) {

    $insert_category = $pdo->prepare("

        INSERT INTO expense_categories
        (
            school_id,
            name
        )

        VALUES
        (
            ?, ?
        )

    ");

    $insert_category->execute([

        $school_id,
        'Salary'

    ]);

    $salary_category_id = $pdo->lastInsertId();
}



// ======================================================
// PAY SALARY
// ======================================================

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

    try {

        $pdo->beginTransaction();


        // ==================================================
        // FORM DATA
        // ==================================================

        $teacher_id = intval($_POST['teacher_id'] ?? 0);

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

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

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


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

        if (

            $teacher_id <= 0
            ||
            $amount <= 0
            ||
            empty($payment_date)
            ||
            empty($month_year)

        ) {

            throw new Exception('Invalid form data');
        }


        // ==================================================
        // VALIDATE TEACHER
        // ==================================================

        $teacher = $pdo->prepare("

            SELECT

                id,
                name

            FROM teachers

            WHERE id = ?
            AND school_id = ?

            LIMIT 1

        ");

        $teacher->execute([

            $teacher_id,
            $school_id

        ]);

        $teacher_data = $teacher->fetch(PDO::FETCH_ASSOC);


        if (!$teacher_data) {

            throw new Exception('Invalid teacher');
        }


        // ==================================================
        // CHECK DUPLICATE SALARY
        // ==================================================

        $check_salary = $pdo->prepare("

            SELECT
                id

            FROM salary_payments

            WHERE school_id = ?
            AND session_id = ?
            AND teacher_id = ?
            AND month_year = ?

            LIMIT 1

        ");

        $check_salary->execute([

            $school_id,
            $current_session_id,
            $teacher_id,
            $month_year

        ]);


        if ($check_salary->fetch()) {

            throw new Exception(
                'Salary already paid for this month'
            );
        }


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

        $receipt_no =

            'SAL-'

            .

            strtoupper(
                substr(md5(uniqid()), 0, 10)
            );


        // ==================================================
        // INSERT SALARY PAYMENT
        // ==================================================

        $salary_insert = $pdo->prepare("

            INSERT INTO salary_payments
            (
                school_id,
                session_id,
                teacher_id,
                amount,
                payment_date,
                month_year,
                receipt_no
            )

            VALUES
            (
                ?, ?, ?, ?, ?, ?, ?
            )

        ");


        $salary_insert->execute([

            $school_id,
            $current_session_id,
            $teacher_id,
            $amount,
            $payment_date,
            $month_year,
            $receipt_no

        ]);


        $salary_id = $pdo->lastInsertId();


        // ==================================================
        // INSERT EXPENSE ENTRY
        // ==================================================

        $description =

            'Salary Paid to '

            .

            $teacher_data['name']

            .

            ' for '

            .

            $month_year;


        $expense = $pdo->prepare("

            INSERT INTO expenses
            (
                school_id,
                session_id,
                category_id,
                description,
                amount,
                payment_mode,
                payment_date,
                receipt_no
            )

            VALUES
            (
                ?, ?, ?, ?, ?, ?, ?, ?
            )

        ");


        $expense->execute([

            $school_id,
            $current_session_id,
            $salary_category_id,
            $description,
            $amount,
            'Bank Transfer',
            $payment_date,
            $receipt_no

        ]);


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

        logActivity($pdo, [

            'school_id' => $school_id,

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

            'module' => 'Salary',

            'action' => 'CREATE',

            'record_id' => $salary_id,

            'message' =>

                "Salary paid to {$teacher_data['name']} for {$month_year}",

            'old_data' => null,

            'new_data' => [

                'teacher_id' => $teacher_id,

                'teacher_name' => $teacher_data['name'],

                'amount' => $amount,

                'payment_date' => $payment_date,

                'month_year' => $month_year,

                'receipt_no' => $receipt_no,

                'session_id' => $current_session_id

            ]

        ]);


        // ==================================================
        // COMMIT
        // ==================================================

        $pdo->commit();


        header(

            "Location: payout.php?msg="

            .

            urlencode('✅ Salary Paid Successfully!')

        );

        exit;

    }

    catch (Exception $e) {

        if ($pdo->inTransaction()) {

            $pdo->rollBack();
        }


        header(

            "Location: payout.php?msg="

            .

            urlencode('❌ ' . $e->getMessage())

        );

        exit;
    }
}




// ======================================================
// UPDATE SALARY
// ======================================================

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

    try {

        $pdo->beginTransaction();


        // ==================================================
        // FORM DATA
        // ==================================================

        $salary_id = intval($_POST['salary_id'] ?? 0);

        $teacher_id = intval($_POST['teacher_id'] ?? 0);

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

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

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


        // ==================================================
        // VALIDATE SALARY RECORD
        // ==================================================

        $salary = $pdo->prepare("

            SELECT *

            FROM salary_payments

            WHERE id = ?
            AND school_id = ?
            AND session_id = ?

            LIMIT 1

        ");

        $salary->execute([

            $salary_id,
            $school_id,
            $current_session_id

        ]);

        $salary_data = $salary->fetch(PDO::FETCH_ASSOC);


        if (!$salary_data) {

            throw new Exception(
                'Salary record not found'
            );
        }


        // ==================================================
        // VALIDATE TEACHER
        // ==================================================

        $teacher = $pdo->prepare("

            SELECT

                id,
                name

            FROM teachers

            WHERE id = ?
            AND school_id = ?

            LIMIT 1

        ");

        $teacher->execute([

            $teacher_id,
            $school_id

        ]);

        $teacher_data = $teacher->fetch(PDO::FETCH_ASSOC);


        if (!$teacher_data) {

            throw new Exception('Invalid teacher');
        }


        // ==================================================
        // CHECK DUPLICATE MONTH
        // ==================================================

        $duplicate = $pdo->prepare("

            SELECT
                id

            FROM salary_payments

            WHERE school_id = ?
            AND session_id = ?
            AND teacher_id = ?
            AND month_year = ?
            AND id != ?

            LIMIT 1

        ");

        $duplicate->execute([

            $school_id,
            $current_session_id,
            $teacher_id,
            $month_year,
            $salary_id

        ]);


        if ($duplicate->fetch()) {

            throw new Exception(
                'Duplicate salary entry found'
            );
        }


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

        $old_data = [

            'teacher_id' => $salary_data['teacher_id'],

            'amount' => $salary_data['amount'],

            'payment_date' => $salary_data['payment_date'],

            'month_year' => $salary_data['month_year']

        ];


        // ==================================================
        // UPDATE SALARY PAYMENT
        // ==================================================

        $update_salary = $pdo->prepare("

            UPDATE salary_payments

            SET

                teacher_id = ?,
                amount = ?,
                payment_date = ?,
                month_year = ?

            WHERE id = ?
            AND school_id = ?
            AND session_id = ?

        ");


        $update_salary->execute([

            $teacher_id,
            $amount,
            $payment_date,
            $month_year,
            $salary_id,
            $school_id,
            $current_session_id

        ]);


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

        $description =

            'Salary Paid to '

            .

            $teacher_data['name']

            .

            ' for '

            .

            $month_year;


        $update_expense = $pdo->prepare("

            UPDATE expenses

            SET

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

            WHERE receipt_no = ?
            AND school_id = ?
            AND session_id = ?

        ");


        $update_expense->execute([

            $salary_category_id,
            $description,
            $amount,
            $payment_date,
            $salary_data['receipt_no'],
            $school_id,
            $current_session_id

        ]);


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

        logActivity($pdo, [

            'school_id' => $school_id,

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

            'module' => 'Salary',

            'action' => 'UPDATE',

            'record_id' => $salary_id,

            'message' =>

                "Salary updated for {$teacher_data['name']}",

            'old_data' => $old_data,

            'new_data' => [

                'teacher_id' => $teacher_id,

                'teacher_name' => $teacher_data['name'],

                'amount' => $amount,

                'payment_date' => $payment_date,

                'month_year' => $month_year

            ]

        ]);


        // ==================================================
        // COMMIT
        // ==================================================

        $pdo->commit();


        header(

            "Location: payout.php?msg="

            .

            urlencode('🔄 Salary Updated Successfully!')

        );

        exit;

    }

    catch (Exception $e) {

        if ($pdo->inTransaction()) {

            $pdo->rollBack();
        }


        header(

            "Location: payout.php?msg="

            .

            urlencode('❌ ' . $e->getMessage())

        );

        exit;
    }
}




// ======================================================
// DELETE SALARY
// ======================================================

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

    try {

        $pdo->beginTransaction();


        $salary_id = intval($_GET['delete'] ?? 0);


        // ==================================================
        // FETCH RECORD
        // ==================================================

        $salary = $pdo->prepare("

            SELECT *

            FROM salary_payments

            WHERE id = ?
            AND school_id = ?
            AND session_id = ?

            LIMIT 1

        ");

        $salary->execute([

            $salary_id,
            $school_id,
            $current_session_id

        ]);

        $salary_data = $salary->fetch(PDO::FETCH_ASSOC);


        if (!$salary_data) {

            throw new Exception(
                'Salary record not found'
            );
        }


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

        logActivity($pdo, [

            'school_id' => $school_id,

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

            'module' => 'Salary',

            'action' => 'DELETE',

            'record_id' => $salary_id,

            'message' =>

                "Salary deleted (Receipt: {$salary_data['receipt_no']})",

            'old_data' => $salary_data,

            'new_data' => null

        ]);


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

        $delete_expense = $pdo->prepare("

            DELETE FROM expenses

            WHERE receipt_no = ?
            AND school_id = ?
            AND session_id = ?

        ");

        $delete_expense->execute([

            $salary_data['receipt_no'],
            $school_id,
            $current_session_id

        ]);


        // ==================================================
        // DELETE SALARY
        // ==================================================

        $delete_salary = $pdo->prepare("

            DELETE FROM salary_payments

            WHERE id = ?
            AND school_id = ?
            AND session_id = ?

        ");

        $delete_salary->execute([

            $salary_id,
            $school_id,
            $current_session_id

        ]);


        // ==================================================
        // COMMIT
        // ==================================================

        $pdo->commit();


        header(

            "Location: payout.php?msg="

            .

            urlencode('🗑️ Salary Deleted Successfully!')

        );

        exit;

    }

    catch (Exception $e) {

        if ($pdo->inTransaction()) {

            $pdo->rollBack();
        }


        header(

            "Location: payout.php?msg="

            .

            urlencode('❌ ' . $e->getMessage())

        );

        exit;
    }
}

?>