<?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 BOOK
// ======================================================

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

    try {

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

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

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

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

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

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

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

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

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

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

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

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

        if ($book_title === '') {

            throw new Exception(
                'Book title required.'
            );
        }

        if ($qty < 0) {

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

        if ($perunitcost < 0) {

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

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

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

            FROM books

            WHERE school_id = ?
            AND book_title = ?

            LIMIT 1
        ");

        $stmt->execute([

            $school_id,
            $book_title

        ]);

        if ($stmt->fetch()) {

            throw new Exception(
                'Book already exists.'
            );
        }

        // ==============================================
        // INSERT
        // ==============================================

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

                school_id,
                book_title,
                book_no,
                isbn_no,
                publish,
                author,
                subject,
                rack_no,
                qty,
                perunitcost,
                postdate,
                description

            )

            VALUES (

                ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?

            )
        ");

        $stmt->execute([

            $school_id,
            $book_title,
            $book_no,
            $isbn_no,
            $publish,
            $author,
            $subject,
            $rack_no,
            $qty,
            $perunitcost,
            $postdate,
            $description

        ]);

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

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

        logActivity($pdo, [

            'school_id' => $school_id,

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

            'module' => 'Library',

            'action' => 'ADD',

            'record_id' => $book_id,

            'message' => 'New book added',

            'new_data' => [

                'book_title' => $book_title,

                'book_no' => $book_no,

                'author' => $author,

                'qty' => $qty,

                'price' => $perunitcost

            ]

        ]);

        echo json_encode([

            'success' => true,

            'message' =>
                'Book added successfully.'

        ]);

        exit;

    } catch (Throwable $e) {

        http_response_code(500);

        echo json_encode([

            'success' => false,

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

        ]);

        exit;
    }
}

// ======================================================
// UPDATE BOOK
// ======================================================

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

    try {

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

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

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

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

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

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

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

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

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

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

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

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

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

        if ($book_id <= 0) {

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

        if ($book_title === '') {

            throw new Exception(
                'Book title required.'
            );
        }

        if ($qty < 0) {

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

        if ($perunitcost < 0) {

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

        // ==============================================
        // VERIFY BOOK
        // ==============================================

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

            FROM books

            WHERE id = ?
            AND school_id = ?

            LIMIT 1
        ");

        $stmt->execute([

            $book_id,
            $school_id

        ]);

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

        if (!$book) {

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

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

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

            FROM books

            WHERE school_id = ?
            AND book_title = ?
            AND id != ?

            LIMIT 1
        ");

        $stmt->execute([

            $school_id,
            $book_title,
            $book_id

        ]);

        if ($stmt->fetch()) {

            throw new Exception(
                'Book already exists.'
            );
        }

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

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

            SET

                book_title = ?,
                book_no = ?,
                isbn_no = ?,
                publish = ?,
                author = ?,
                subject = ?,
                rack_no = ?,
                qty = ?,
                perunitcost = ?,
                postdate = ?,
                description = ?

            WHERE id = ?
            AND school_id = ?
        ");

        $stmt->execute([

            $book_title,
            $book_no,
            $isbn_no,
            $publish,
            $author,
            $subject,
            $rack_no,
            $qty,
            $perunitcost,
            $postdate,
            $description,
            $book_id,
            $school_id

        ]);

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

        logActivity($pdo, [

            'school_id' => $school_id,

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

            'module' => 'Library',

            'action' => 'UPDATE',

            'record_id' => $book_id,

            'message' => 'Book updated',

            'new_data' => [

                'book_title' => $book_title,

                'author' => $author,

                'qty' => $qty,

                'price' => $perunitcost

            ]

        ]);

        echo json_encode([

            'success' => true,

            'message' =>
                'Book updated successfully.'

        ]);

        exit;

    } catch (Throwable $e) {

        http_response_code(500);

        echo json_encode([

            'success' => false,

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

        ]);

        exit;
    }
}

// ======================================================
// DELETE BOOK
// ======================================================

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

    try {

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

        if ($book_id <= 0) {

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

        // ==============================================
        // VERIFY BOOK
        // ==============================================

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

            FROM books

            WHERE id = ?
            AND school_id = ?

            LIMIT 1
        ");

        $stmt->execute([

            $book_id,
            $school_id

        ]);

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

        if (!$book) {

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

        // ==============================================
        // CHECK ISSUED BOOK
        // ==============================================

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

            FROM book_issues

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

            LIMIT 1
        ");

        $stmt->execute([

            $school_id,
            $book_id

        ]);

        if ($stmt->fetch()) {

            throw new Exception(
                'Book currently issued.'
            );
        }

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

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

            WHERE id = ?
            AND school_id = ?
        ");

        $stmt->execute([

            $book_id,
            $school_id

        ]);

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

        logActivity($pdo, [

            'school_id' => $school_id,

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

            'module' => 'Library',

            'action' => 'DELETE',

            'record_id' => $book_id,

            'message' => 'Book deleted',

            'old_data' => $book

        ]);

        echo json_encode([

            'success' => true,

            'message' =>
                'Book deleted successfully.'

        ]);

        exit;

    } catch (Throwable $e) {

        http_response_code(500);

        echo json_encode([

            'success' => false,

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

        ]);

        exit;
    }
}
?>