<?php
// api/library.php

require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/session_auth.php';
rvu_audit_context_from_request($pdo);

header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: Content-Type, Authorization");
header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { http_response_code(204); exit; }

$method = $_SERVER['REQUEST_METHOD'];
$path_info = isset($_SERVER['PATH_INFO']) && trim((string)$_SERVER['PATH_INFO'], '/') !== ''
    ? explode('/', trim((string)$_SERVER['PATH_INFO'], '/'))
    : [];
$resource = $path_info[0] ?? (isset($_GET['resource']) ? trim((string)$_GET['resource']) : '');
$action_or_id = $path_info[1] ?? null;
$third_part = $path_info[2] ?? null;

// Query-string routes are reliable on shared cPanel hosting even when Apache
// does not pass PATH_INFO after a .php script. Keep legacy PATH_INFO routes
// working for existing clients.
if (!$path_info && $resource !== '') {
    $query_id = isset($_GET['id']) ? trim((string)$_GET['id']) : null;
    $query_action = isset($_GET['action']) ? trim((string)$_GET['action']) : null;
    $query_reference = isset($_GET['reference']) ? trim((string)$_GET['reference']) : null;

    if ($resource === 'borrow-records' && $query_action !== null && $query_action !== '') {
        $action_or_id = $query_action;
        $third_part = $query_reference;
    } elseif ($resource === 'students') {
        $action_or_id = $query_id;
        $third_part = $query_action;
    } else {
        $action_or_id = $query_id;
    }
}

$raw_input = file_get_contents("php://input");
$input = [];
if (trim($raw_input) !== '') {
    $decoded = json_decode($raw_input);
    if (json_last_error() !== JSON_ERROR_NONE || !is_object($decoded)) {
        respond(400, ["detail" => "Request body must be a valid JSON object."]);
    }
    $input = json_decode($raw_input, true);
}

function respond($code, $data) {
    http_response_code($code);
    echo json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    exit;
}

function cleanText($value) {
    if (!is_string($value) && !is_int($value) && !is_float($value)) return '';
    $text = trim((string)$value);
    return strtolower($text) === 'null' ? '' : $text;
}

// Validate dynamic column names before interpolating them into SQL.
function validateColumns($input) {
    foreach (array_keys($input) as $key) {
        if (!is_string($key) || !preg_match('/^[a-z_][a-z0-9_]*$/i', $key)) {
            respond(400, ["detail" => "Invalid field name."]);
        }
    }
}

function cleanDateTime($value, $default = null) {
    if (!is_string($value) && $value !== null) return $default;
    if ($value === null || trim((string)$value) === '') return $default;
    try { return (new DateTime($value))->format('Y-m-d H:i:s'); }
    catch (Exception $e) { return $default; }
}

try {

    // ============================================================
    // BOOKS
    // ============================================================

    if ($resource === 'books') {

        if ($method === 'GET') {
            $stmt = $pdo->query("SELECT * FROM books ORDER BY id DESC");
            respond(200, $stmt->fetchAll(PDO::FETCH_ASSOC));
        }

        elseif ($method === 'POST') {
            if (empty($input)) respond(400, ["detail" => "No book data supplied."]);

            validateColumns($input);
            $fields = implode(', ', array_keys($input));
            $placeholders = implode(', ', array_fill(0, count($input), '?'));

            $stmt = $pdo->prepare("INSERT INTO books ($fields) VALUES ($placeholders)");
            $stmt->execute(array_values($input));

            respond(201, ["message" => "Book added successfully"]);
        }

        elseif ($method === 'PUT' && $action_or_id) {
            $book_id = $action_or_id;

            if (empty($input)) respond(400, ["detail" => "No book data supplied."]);

            unset($input['id']);
            if (empty($input)) respond(400, ["detail" => "No editable fields supplied."]);
            validateColumns($input);

            $fields = [];
            $params = [];

            foreach ($input as $key => $value) { $fields[] = "$key = ?"; $params[] = $value; }

            $params[] = $book_id;

            $stmt = $pdo->prepare("UPDATE books SET " . implode(', ', $fields) . " WHERE id = ?");
            $stmt->execute($params);

            respond(200, ["message" => "Book updated successfully", "book_id" => $book_id]);
        }

        respond(405, ["detail" => "Method not allowed."]);
    }


    // ============================================================
    // BORROW RECORDS
    // ============================================================

    elseif ($resource === 'borrow-records') {

        // --------------------------------------------------------
        // GET ALL BORROWING RECORDS
        // --------------------------------------------------------

        if ($method === 'GET' && !$action_or_id) {
            $stmt = $pdo->query("SELECT * FROM borrow_records ORDER BY borrow_date DESC NULLS LAST");
            respond(200, $stmt->fetchAll(PDO::FETCH_ASSOC));
        }


        // --------------------------------------------------------
        // ISSUE / BORROW BOOK
        // --------------------------------------------------------

        elseif ($method === 'POST' && $action_or_id === 'issue') {

            $student_id = cleanText($input['student_id'] ?? null);
            $book_id = cleanText($input['book_id'] ?? null);
            $campus = is_string($input['campus'] ?? null) ? cleanText($input['campus']) : '';
            $remarks = cleanText($input['remarks'] ?? null);

            $borrow_date = cleanDateTime($input['borrow_date'] ?? date('Y-m-d H:i:s'), null);
            $due_date = cleanDateTime($input['due_date'] ?? null, null);

            if ($student_id === '') respond(400, ["detail" => "student_id is required."]);
            if ($book_id === '') respond(400, ["detail" => "book_id is required."]);
            if ($campus === '') respond(400, ["detail" => "Enter a valid issuing campus in the issuance form."]);
            if ($borrow_date === null) respond(400, ["detail" => "A valid borrow_date is required."]);
            if ($due_date === null) respond(400, ["detail" => "A valid due_date is required."]);

            if (strtotime($due_date) <= strtotime($borrow_date)) {
                respond(400, ["detail" => "due_date must be after borrow_date."]);
            }

            $student_stmt = $pdo->prepare("SELECT 1 FROM library_students WHERE id = ?");
            $student_stmt->execute([$student_id]);
            if (!$student_stmt->fetchColumn()) {
                respond(404, ["detail" => "Student not found in the library directory."]);
            }

            $pdo->beginTransaction();

            // Lock the book while issuing so two users cannot borrow the same last copy simultaneously.
            $book_stmt = $pdo->prepare("SELECT * FROM books WHERE id = ? FOR UPDATE");
            $book_stmt->execute([$book_id]);
            $book = $book_stmt->fetch(PDO::FETCH_ASSOC);

            if (!$book) {
                $pdo->rollBack();
                respond(404, ["detail" => "Book not found."]);
            }

            // If the books table has a copies column, verify availability.
            if (array_key_exists('copies', $book) && (int)$book['copies'] <= 0) {
                $pdo->rollBack();
                respond(409, ["detail" => "No available copies of this book."]);
            }

            // Generate a unique reference number.
            do {
                $ref_no = 'TX-' . strtoupper(substr(bin2hex(random_bytes(4)), 0, 6));
                $check = $pdo->prepare("SELECT 1 FROM borrow_records WHERE ref_no = ?");
                $check->execute([$ref_no]);
            } while ($check->fetchColumn());

            // Your table contains ONLY these fields.
            $stmt = $pdo->prepare("INSERT INTO borrow_records (ref_no, student_id, book_id, borrow_date, due_date, status, remarks, campus) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
            $stmt->execute([$ref_no, $student_id, $book_id, $borrow_date, $due_date, 'Borrowed', $remarks, $campus]);

            // Reduce available copies if your books table has copies.
            if (array_key_exists('copies', $book)) {
                $remaining = (int)$book['copies'] - 1;
                $book_status = $remaining <= 0 ? 'Borrowed' : 'Available';

                $update_book = $pdo->prepare("UPDATE books SET copies = copies - 1, status = ? WHERE id = ? AND copies > 0");
                $update_book->execute([$book_status, $book_id]);

                if ($update_book->rowCount() === 0) {
                    $pdo->rollBack();
                    respond(409, ["detail" => "The book could not be issued because no copies are available."]);
                }
            }

            $pdo->commit();

            respond(201, [
                "message" => "Book issued successfully",
                "ref_no" => $ref_no,
                "student_id" => $student_id,
                "book_id" => $book_id,
                "borrow_date" => $borrow_date,
                "due_date" => $due_date,
                "status" => "Borrowed",
                "remarks" => $remarks,
                "campus" => $campus
            ]);
        }


        // --------------------------------------------------------
        // RETURN BOOK
        // --------------------------------------------------------

        elseif ($method === 'POST' && $action_or_id === 'return' && $third_part) {

            $ref_no = urldecode($third_part);

            $pdo->beginTransaction();

            $stmt = $pdo->prepare("SELECT * FROM borrow_records WHERE ref_no = ? FOR UPDATE");
            $stmt->execute([$ref_no]);
            $record = $stmt->fetch(PDO::FETCH_ASSOC);

            if (!$record) {
                $pdo->rollBack();
                respond(404, ["detail" => "Borrowing record not found."]);
            }

            if (strtoupper(trim((string)$record['status'])) === 'RETURNED') {
                $pdo->rollBack();
                respond(409, ["detail" => "This book has already been returned."]);
            }

            $book_id = $record['book_id'];

            $update_record = $pdo->prepare("UPDATE borrow_records SET status = 'Returned' WHERE ref_no = ?");
            $update_record->execute([$ref_no]);

            $book_stmt = $pdo->prepare("SELECT * FROM books WHERE id = ? FOR UPDATE");
            $book_stmt->execute([$book_id]);
            $book = $book_stmt->fetch(PDO::FETCH_ASSOC);
            if (!$book) {
                $pdo->rollBack();
                respond(404, ["detail" => "Book not found; the return was not recorded."]);
            }
            if (array_key_exists('copies', $book)) {
                $update_book = $pdo->prepare("UPDATE books SET copies = copies + 1, status = 'Available' WHERE id = ?");
                $update_book->execute([$book_id]);
            }

            $pdo->commit();

            respond(200, ["message" => "Book returned successfully", "ref_no" => $ref_no, "book_id" => $book_id]);
        }

        respond(405, ["detail" => "Method not allowed for borrow records."]);
    }


    // ============================================================
    // STUDENTS
    // ============================================================

    elseif ($resource === 'students') {

        // --------------------------------------------------------
        // GET STUDENTS
        // --------------------------------------------------------

        if ($method === 'GET' && !$action_or_id) {
            $stmt = $pdo->query("SELECT * FROM library_students ORDER BY id ASC");
            respond(200, $stmt->fetchAll(PDO::FETCH_ASSOC));
        }


        // --------------------------------------------------------
        // STUDENT BORROWING HISTORY
        // --------------------------------------------------------

        elseif ($method === 'GET' && $action_or_id && $third_part === 'history') {
            $stmt = $pdo->prepare("SELECT * FROM borrow_records WHERE student_id = ? ORDER BY borrow_date DESC NULLS LAST");
            $stmt->execute([$action_or_id]);

            respond(200, $stmt->fetchAll(PDO::FETCH_ASSOC));
        }


        // --------------------------------------------------------
        // ADD STUDENT
        // --------------------------------------------------------

        elseif ($method === 'POST') {
            if (empty($input)) respond(400, ["detail" => "No student data supplied."]);

            validateColumns($input);
            $fields = implode(', ', array_keys($input));
            $placeholders = implode(', ', array_fill(0, count($input), '?'));

            $stmt = $pdo->prepare("INSERT INTO library_students ($fields) VALUES ($placeholders)");
            $stmt->execute(array_values($input));

            respond(201, ["message" => "Student registered successfully"]);
        }


        // --------------------------------------------------------
        // UPDATE STUDENT
        // --------------------------------------------------------

        elseif ($method === 'PUT' && $action_or_id) {
            if (empty($input)) respond(400, ["detail" => "No student data supplied."]);

            unset($input['id']);
            if (empty($input)) respond(400, ["detail" => "No editable fields supplied."]);
            validateColumns($input);

            $fields = [];
            $params = [];

            foreach ($input as $key => $value) { $fields[] = "$key = ?"; $params[] = $value; }

            $params[] = $action_or_id;

            $stmt = $pdo->prepare("UPDATE library_students SET " . implode(', ', $fields) . " WHERE id = ?");
            $stmt->execute($params);

            respond(200, ["message" => "Student updated successfully", "student_id" => $action_or_id]);
        }

        respond(405, ["detail" => "Method not allowed for students."]);
    }


    // ============================================================
    // UNKNOWN ROUTE
    // ============================================================

    else {
        respond(404, ["detail" => "Library API route not found.", "resource" => $resource]);
    }


} catch (Throwable $e) {

    if (isset($pdo) && $pdo instanceof PDO && $pdo->inTransaction()) { $pdo->rollBack(); }

    respond(500, ["detail" => $e->getMessage()]);
}
?>