<?php

declare(strict_types=1);

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

header('Content-Type: application/json');

allow_roles(['admin', 'teacher']);

$school_id = (int) $_SESSION['school_id'];

$action = trim($_POST['action'] ?? $_GET['action'] ?? '');

// ======================================================
// VALID ACTIONS
// ======================================================

$allowed_actions = [

    'add',
    'update',
    'delete'

];

if (!in_array($action, $allowed_actions, true)) {

    http_response_code(400);

    echo json_encode([

        'success' => false,
        'message' => 'Invalid action.'

    ]);

    exit;
}

// ======================================================
// ADD MEMBER
// ======================================================

if ($action === 'add') {

    try {

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

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

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

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

        if (
            !in_array(
                $user_type,
                ['Student', 'Teacher'],
                true
            )
        ) {

            throw new Exception(
                'Invalid user type.'
            );
        }

        if ($reference_id <= 0) {

            throw new Exception(
                'Invalid user selected.'
            );
        }

        if ($card_no === '') {

            throw new Exception(
                'Library card number required.'
            );
        }

        // ==============================================
        // DUPLICATE CARD CHECK
        // ==============================================

        $stmt = $pdo->prepare("
            SELECT id

            FROM library_members

            WHERE school_id = ?
            AND card_no = ?

            LIMIT 1
        ");

        $stmt->execute([

            $school_id,
            $card_no

        ]);

        if ($stmt->fetch()) {

            throw new Exception(
                'Library card already exists.'
            );
        }

        // ==============================================
        // VALIDATE USER
        // ==============================================

        if ($user_type === 'Student') {

            $stmt = $pdo->prepare("
                SELECT id

                FROM students

                WHERE id = ?
                AND school_id = ?

                LIMIT 1
            ");

        } else {

            $stmt = $pdo->prepare("
                SELECT id

                FROM teachers

                WHERE id = ?
                AND school_id = ?

                LIMIT 1
            ");
        }

        $stmt->execute([

            $reference_id,
            $school_id

        ]);

        if (!$stmt->fetch()) {

            throw new Exception(
                'Selected user not found.'
            );
        }

        // ==============================================
        // INSERT MEMBER
        // ==============================================

        $stmt = $pdo->prepare("
            INSERT INTO library_members (

                school_id,
                user_type,
                reference_id,
                card_no,
                status

            )

            VALUES (

                ?, ?, ?, ?, ?

            )
        ");

        $stmt->execute([

            $school_id,
            $user_type,
            $reference_id,
            $card_no,
            'Active'

        ]);

        $member_id = (int)
            $pdo->lastInsertId();

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

        logActivity($pdo, [

            'school_id' => $school_id,

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

            'module' => 'Library',

            'action' => 'ADD',

            'record_id' => $member_id,

            'message' => 'Library member added',

            'new_data' => [

                'user_type'   => $user_type,
                'reference_id'=> $reference_id,
                'card_no'     => $card_no

            ]

        ]);

        echo json_encode([

            'success' => true,

            'message' =>
                'Library member added successfully.'

        ]);

        exit;

    } catch (Throwable $e) {

        http_response_code(500);

        echo json_encode([

            'success' => false,

            'message' => $e->getMessage()

        ]);

        exit;
    }
}

// ======================================================
// UPDATE MEMBER
// ======================================================

if ($action === 'update') {

    try {

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

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

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

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

        if ($member_id <= 0) {

            throw new Exception(
                'Invalid member.'
            );
        }

        if ($card_no === '') {

            throw new Exception(
                'Card number required.'
            );
        }

        if (
            !in_array(
                $status,
                ['Active', 'Inactive'],
                true
            )
        ) {

            throw new Exception(
                'Invalid status.'
            );
        }

        // ==============================================
        // VERIFY MEMBER
        // ==============================================

        $stmt = $pdo->prepare("
            SELECT *

            FROM library_members

            WHERE id = ?
            AND school_id = ?

            LIMIT 1
        ");

        $stmt->execute([

            $member_id,
            $school_id

        ]);

        $member = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$member) {

            throw new Exception(
                'Member not found.'
            );
        }

        // ==============================================
        // DUPLICATE CARD CHECK
        // ==============================================

        $stmt = $pdo->prepare("
            SELECT id

            FROM library_members

            WHERE school_id = ?
            AND card_no = ?
            AND id != ?

            LIMIT 1
        ");

        $stmt->execute([

            $school_id,
            $card_no,
            $member_id

        ]);

        if ($stmt->fetch()) {

            throw new Exception(
                'Card number already exists.'
            );
        }

        // ==============================================
        // UPDATE
        // ==============================================

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

            SET

                card_no = ?,
                status = ?

            WHERE id = ?
            AND school_id = ?
        ");

        $stmt->execute([

            $card_no,
            $status,
            $member_id,
            $school_id

        ]);

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

        logActivity($pdo, [

            'school_id' => $school_id,

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

            'module' => 'Library',

            'action' => 'UPDATE',

            'record_id' => $member_id,

            'message' => 'Library member updated',

            'new_data' => [

                'card_no' => $card_no,
                'status'  => $status

            ]

        ]);

        echo json_encode([

            'success' => true,

            'message' =>
                'Member updated successfully.'

        ]);

        exit;

    } catch (Throwable $e) {

        http_response_code(500);

        echo json_encode([

            'success' => false,

            'message' => $e->getMessage()

        ]);

        exit;
    }
}

// ======================================================
// DELETE MEMBER
// ======================================================

if ($action === 'delete') {

    try {

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

        if ($member_id <= 0) {

            throw new Exception(
                'Invalid member.'
            );
        }

        // ==============================================
        // VERIFY MEMBER
        // ==============================================

        $stmt = $pdo->prepare("
            SELECT *

            FROM library_members

            WHERE id = ?
            AND school_id = ?

            LIMIT 1
        ");

        $stmt->execute([

            $member_id,
            $school_id

        ]);

        $member = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$member) {

            throw new Exception(
                'Member not found.'
            );
        }

        // ==============================================
        // CHECK ACTIVE ISSUES
        // ==============================================

        $stmt = $pdo->prepare("
            SELECT id

            FROM book_issues

            WHERE member_id = ?
            AND school_id = ?
            AND status = 'Issued'

            LIMIT 1
        ");

        $stmt->execute([

            $member_id,
            $school_id

        ]);

        if ($stmt->fetch()) {

            throw new Exception(
                'Cannot delete member with issued books.'
            );
        }

        // ==============================================
        // DELETE
        // ==============================================

        $stmt = $pdo->prepare("
            DELETE FROM library_members

            WHERE id = ?
            AND school_id = ?
        ");

        $stmt->execute([

            $member_id,
            $school_id

        ]);

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

        logActivity($pdo, [

            'school_id' => $school_id,

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

            'module' => 'Library',

            'action' => 'DELETE',

            'record_id' => $member_id,

            'message' => 'Library member deleted',

            'old_data' => $member

        ]);

        echo json_encode([

            'success' => true,

            'message' =>
                'Member deleted successfully.'

        ]);

        exit;

    } catch (Throwable $e) {

        http_response_code(500);

        echo json_encode([

            'success' => false,

            'message' => $e->getMessage()

        ]);

        exit;
    }
}
?>