<?php
header('Content-Type: application/json');
require_once "../config.php";

// ----------------- Normal return via GET (no fine) -----------------
if (isset($_POST['id'])) {
    $issue_id = $_POST['id'] ?? $_GET['id'];
    $adminId   = $_POST['adminId'];
    $currentTime = $_POST['currentTime'];

    $sql = "SELECT BookId, CopyId, fine, ReturnDate FROM tblissuedbookdetails WHERE id=:issue_id";
    $query = $dbh->prepare($sql);
    $query->bindParam(':issue_id', $issue_id, PDO::PARAM_INT);
    $query->execute();
    $issue = $query->fetch(PDO::FETCH_OBJ);


    if ($issue && empty($issue->ReturnDate)) {
        if (!empty($issue->ReturnDate)) {
            echo json_encode(["status" => "error", "message" => "Book is already returned"]);
            exit;
        }

        if ($issue->fine > 0) {
            echo json_encode(["status" => "error", "message" => "Please collect fine ₹" . $issue->fine]);
            exit;
        }

        $returndate = date('Y-m-d H:i:s');

        $updateSql = "UPDATE tblissuedbookdetails SET ReturnDate=:returndate, RetrunStatus=1, modified_by = :adminId, modified_on = :currentTime WHERE id=:issue_id";
        $updateQuery = $dbh->prepare($updateSql);
        $updateQuery->bindParam(':returndate', $returndate);
        $updateQuery->bindParam(':adminId', $adminId);
        $updateQuery->bindParam(':currentTime', $currentTime);
        $updateQuery->bindParam(':issue_id', $issue_id, PDO::PARAM_INT);
        $updateQuery->execute();

        $updateCopy = $dbh->prepare("UPDATE tblbookcopies SET book_status='available' WHERE id=:copyid");
        $updateCopy->bindParam(':copyid', $issue->CopyId, PDO::PARAM_INT);
        $updateCopy->execute();

        $updateBook = $dbh->prepare("UPDATE tblbooks SET current_count=current_count+1 WHERE id=:bookid");
        $updateBook->bindParam(':bookid', $issue->BookId, PDO::PARAM_INT);
        $updateBook->execute();

        echo json_encode(["status" => "success", "message" => "Return Status Update Successfully"]);
    } else {
        echo json_encode(["status" => "error", "message" => "Return Status Not Update"]);
    }
    exit;
}

$adminId   = $_POST['adminId'];
$borrowerid   = strtoupper($_POST['borrowID']);
$borrowertype = $_POST['borrowType'];
$copyid       = intval($_POST['bookDetails']);
$days         = intval($_POST['days'] ?? 0);
$months       = intval($_POST['months'] ?? 0);
$currentTime = $_POST['currentTime'];

$duedate   = date('Y-m-d', strtotime("+$months months +$days days"));
$issuedate = date("Y-m-d H:i:s");

$checkSql = "SELECT c.id, c.book_no, c.book_status, b.id as bookid
             FROM tblbookcopies c
             JOIN tblbooks b ON c.book_id = b.id
             WHERE c.id = :copyid AND c.book_status = 'available'";
$checkQuery = $dbh->prepare($checkSql);
$checkQuery->bindParam(':copyid', $copyid, PDO::PARAM_INT);
$checkQuery->execute();
$copy = $checkQuery->fetch(PDO::FETCH_OBJ);

if ($copy) {
    $sql = "INSERT INTO tblissuedbookdetails
            (BorrowerID, BorrowerType, BookId, CopyId, DueDate, IssuesDate, created_by, created_on)
            VALUES (:borrowerid, :borrowertype, :bookid, :copyid, :duedate, :issuedate, :adminId, :currentTime)";
    $query = $dbh->prepare($sql);
    $query->bindParam(':borrowerid', $borrowerid);
    $query->bindParam(':borrowertype', $borrowertype);
    $query->bindParam(':bookid', $copy->bookid, PDO::PARAM_INT);
    $query->bindParam(':copyid', $copyid, PDO::PARAM_INT);
    $query->bindParam(':duedate', $duedate);
    $query->bindParam(':issuedate', $issuedate);
    $query->bindParam(':adminId', $adminId);
    $query->bindParam(':currentTime', $currentTime);
    $query->execute();

    $lastId = $dbh->lastInsertId();
    if ($lastId) {
        $updateSql = "UPDATE tblbookcopies SET book_status = 'issued' WHERE id = :copyid";
        $upd = $dbh->prepare($updateSql);
        $upd->bindParam(':copyid', $copyid, PDO::PARAM_INT);
        $upd->execute();

        $reduceSql = "UPDATE tblbooks
                      SET current_count = current_count - 1
                      WHERE id = :bookid AND current_count > 0";
        $reduce = $dbh->prepare($reduceSql);
        $reduce->bindParam(':bookid', $copy->bookid, PDO::PARAM_INT);
        $reduce->execute();

        echo json_encode(['status' => 'success', 'message' => 'Book copy issued successfully.']);
    } else {
        echo json_encode(['status' => 'error', 'message' => 'Insert failed.']);
    }
} else {
    echo json_encode(['status' => 'error', 'message' => 'Book not available.']);
}
