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

try {
    $issue_id = intval($_POST['issue_id'] ?? 0);
    if ($issue_id <= 0) {
        echo json_encode(['status' => 'error', 'message' => 'Invalid issue id']);
        exit;
    }

    // Payment status must be provided
    $payment_status = trim($_POST['payment_status'] ?? '');
    if ($payment_status !== 'Paid' && $payment_status !== 'Unpaid') {
        echo json_encode(['status' => 'error', 'message' => 'Invalid payment status']);
        exit;
    }

    $actual_amount = trim($_POST['actual_amount']) ??  trim($_POST['fine_amount']);
    $fine_amount = trim($_POST['fine_amount'] ?? '');
    $payment_mode = $payment_status === 'Unpaid' ? null : trim($_POST['payment_mode']);
    $remarks = trim($_POST['remarks'] ?? '');
    $payment_date = date('Y-m-d H:i:s');

    try {
        // fetch issue info
        $q = $dbh->prepare("SELECT BookId, CopyId, DueDate, ReturnDate FROM tblissuedbookdetails WHERE id = :id LIMIT 1");
        $q->bindParam(':id', $issue_id, PDO::PARAM_INT);
        $q->execute();
        $issue = $q->fetch(PDO::FETCH_OBJ);
        if (!$issue) {
            echo json_encode(['status' => 'error', 'message' => 'Issue record not found.']);
            exit;
        }

        // Insert into tblfine_payments
        $ins = $dbh->prepare("INSERT INTO tblfine_payments (tblissuedbookdetailsid, fine_amount, payment_status, payment_mode, actual_amount, remarks, payment_date)
    VALUES (:issue_id, :fine_amount, :payment_status, :payment_mode, :actual_amount, :remarks, :payment_date)");
        $ins->bindValue(':issue_id', $issue_id, PDO::PARAM_INT);
        $ins->bindValue(':fine_amount', $fine_amount);
        $ins->bindValue(':payment_status', $payment_status);
        $ins->bindValue(':payment_mode', $payment_mode);
        if ($actual_amount === null) $ins->bindValue(':actual_amount', null, PDO::PARAM_NULL);
        else $ins->bindValue(':actual_amount', $actual_amount);
        $ins->bindValue(':remarks', $remarks);
        $ins->bindValue(':payment_date', $payment_date);
        $ins->execute();
        $returndate = $payment_date;
        $upd = $dbh->prepare("UPDATE tblissuedbookdetails SET fine = :fine, ReturnDate = :returndate, RetrunStatus = 1 WHERE id = :id");
        $upd->bindValue(':fine', $fine_amount);
        $upd->bindValue(':returndate', $returndate);
        $upd->bindValue(':id', $issue_id, PDO::PARAM_INT);
        $upd->execute();

        // Update copy to available
        $updCopy = $dbh->prepare("UPDATE tblbookcopies SET book_status = 'available' WHERE id = :copyid");
        $updCopy->bindValue(':copyid', $issue->CopyId, PDO::PARAM_INT);
        $updCopy->execute();

        // Increment book current_count
        $updBook = $dbh->prepare("UPDATE tblbooks SET current_count = current_count + 1 WHERE id = :bookid");
        $updBook->bindValue(':bookid', $issue->BookId, PDO::PARAM_INT);
        $updBook->execute();

        echo json_encode(['status' => 'success', 'message' => "Fine collected ₹" . number_format((float)$fine_amount, 2) . ". Book returned."]);
        exit;
    } catch (Exception $e) {
        // error
        echo json_encode(['status' => 'error', 'message' => 'Server error: ' . $e->getMessage()]);
        exit;
    }
} catch (Exception $e) {
    echo json_encode(['status' => 'error', 'message' => 'Server error: ' . $e->getMessage()]);
    exit;
}
