<?php
session_start();
error_reporting(0);
include('includes/config.php');

date_default_timezone_set('Asia/Kolkata'); // Important for correct date/time

if (strlen($_SESSION['staff_login']) == 0) {
    header('location:index.php');
    exit;
}

$borrowerId = $_SESSION['staffid'];

// -------- Auto-cancel pending extensions at 1 PM --------
$today = date('Y-m-d');
$nowHour = date('H'); // current hour in 24h format
$decisiondate = date('Y-m-d H:i:s');
if ($nowHour >= 23) { // 123 = 11 PM
    $cancelQ = $dbh->prepare("
        UPDATE tblbook_extensions e
        JOIN tblissuedbookdetails ib ON e.issue_id = ib.id
        SET e.status = 'Cancelled',
            e.decision_date = :decision_date
            e.admin_remark = 'Auto-cancelled: Admin did not approve by 1 PM'
        WHERE e.status = 'Pending'
          AND DATE(ib.DueDate) = :today
          AND ib.BorrowerID = :sid
    ");
    $cancelQ->execute([':today' => $today, ':sid' => $borrowerId, ':decision_date' => $decisiondate]);

    if ($cancelQ->rowCount() > 0) {
        $_SESSION['error'] = "❌ Your extension request(s) for today were auto-cancelled because the admin did not approve them by 1 PM.";
    }
}

// -------- Helper: fine calculation --------
function compute_fine_amount(PDO $dbh, int $issue_id, ?string $dueDateStr = null): float
{
    $perDayFine = 10; // Rs 10 per day
    if (!$dueDateStr)
        return 0;
    $dueDate = new DateTime($dueDateStr);
    $today = new DateTime('today');
    if ($today <= $dueDate)
        return 0;
    $days = $dueDate->diff($today)->days;
    return $days * $perDayFine;
}

// -------- Handle Extension Request --------
if (isset($_POST['request_extension'])) {
    $issueId = intval($_POST['issue_id']);
    $days = intval($_POST['days']);

    // Check extension count (approved + pending)
    $chk = $dbh->prepare("SELECT COUNT(*) FROM tblbook_extensions WHERE issue_id = :iid AND requested_by = :sid");
    $chk->execute([':iid' => $issueId, ':sid' => $borrowerId]);
    $extCount = (int) $chk->fetchColumn();

    if ($extCount >= 2) {
        $_SESSION['error'] = "❌ You can request only 2 extensions for this book.";
    } else {
        // Fetch current final due: last approved extension (if exists) else original DueDate
        $q = $dbh->prepare("SELECT ib.DueDate,
                                  (SELECT requested_due_date FROM tblbook_extensions 
                                       WHERE issue_id = :iid AND status='Approved' 
                                       ORDER BY id DESC LIMIT 1) AS lastApprovedDue
                             FROM tblissuedbookdetails ib
                             WHERE ib.id = :iid AND ib.BorrowerID = :sid");
        $q->execute([':iid' => $issueId, ':sid' => $borrowerId]);
        $row = $q->fetch(PDO::FETCH_OBJ);

        if ($row) {
            $todayDate = new DateTime('today');
            $currentDueStr = $row->lastApprovedDue ?: $row->DueDate;
            if (!$currentDueStr) {
                $_SESSION['error'] = "❌ Due date not found for this issue.";
            } else {
                $currentDue = (new DateTime($currentDueStr))->setTime(0, 0, 0);

                if ($todayDate <= $currentDue) {
                    $newDue = (new DateTime($currentDueStr))->modify("+{$days} days")->format('Y-m-d');
                    $ins = $dbh->prepare("INSERT INTO tblbook_extensions(issue_id, requested_days, requested_due_date, status, requested_by, requested_on) 
                                          VALUES(:iid, :days, :newdue, 'Pending', :sid, :req_on)");
                    $ins->execute([
                        ':iid' => $issueId,
                        ':days' => $days,
                        ':newdue' => $newDue,
                        ':sid' => $borrowerId,
                        'req_on' => date('Y-m-d H:i:s')
                    ]);
                    $_SESSION['msg'] = "✅ Extension request submitted successfully!";
                } else {
                    $_SESSION['error'] = "❌ You can only request on or before the current due date.";
                }
            }
        } else {
            $_SESSION['error'] = "❌ Issue not found or does not belong to you.";
        }
    }
    header("Location: staff-issued-book.php");
    exit;
}

// -------- Filters --------
$bookname = $_GET['bookname'] ?? '';
$from = $_GET['from'] ?? '';
$to = $_GET['to'] ?? '';
$status = $_GET['status'] ?? 'notreturned';
?>

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8" />
    <title>My Borrowed Books | Library System</title>
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <link rel="icon" type="image/x-icon" href="../<?php echo $_SESSION['logo']; ?>">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <link href="https://cdn.datatables.net/1.13.6/css/dataTables.bootstrap4.min.css" rel="stylesheet">
    <link href="https://cdn.datatables.net/buttons/2.4.1/css/buttons.bootstrap4.min.css" rel="stylesheet">
    <style>
        .square-card {
            background-color: #f8f9fa;
            border: 1px solid #dee2e6;
            border-radius: 5px;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.05);
        }

        .header-line {
            color: #0d6efd;
            font-size: 20px;
        }

        .table-wrapper {
            overflow-x: auto;
            padding: 10px;
        }

        .status-btn {
            border-width: 2px;
            font-weight: 600;
            transition: all 0.25s ease;
        }

        .status-btn i {
            margin-right: 6px;
        }

        /* Active / Selected state */
        .status-btn.active {
            color: #fff !important;
        }

        .btn-outline-success.active {
            background-color: #28a745;
            border-color: #28a745;
        }

        .btn-outline-danger.active {
            background-color: #dc3545;
            border-color: #dc3545;
        }

        /* Hover polish */
        .status-btn:hover {
            transform: translateY(-1px);
        }

        .no-wrap {
            white-space: nowrap;
        }
    </style>
</head>

<body>
    <div class="d-flex flex-column min-vh-100">
        <?php include('includes/header.php'); ?>

        <div class="main-content flex-grow-1 p-4">
            <div class="row pad-botm mb-4">
                <div class="col-md-12">
                    <h5 class="header-line"><i class="fa fa-book-reader mr-2"></i>MY BORROWED BOOKS</h5>
                </div>
            </div>

            <!-- Messages -->
            <?php if (!empty($_SESSION['msg'])) {
                echo "<div class='alert alert-success'>" . $_SESSION['msg'] . "</div>";
                unset($_SESSION['msg']);
            } ?>
            <?php if (!empty($_SESSION['error'])) {
                echo "<div class='alert alert-danger'>" . $_SESSION['error'] . "</div>";
                unset($_SESSION['error']);
            } ?>

            <!-- Filter Form -->
            <form method="get" class="row justify-content-center mb-4">
                <!-- <div class="col-md-2 mb-2">
                    <input type="text" name="bookname" class="form-control" placeholder="Book Name"
                        value="<?= htmlentities($bookname) ?>">
                </div> -->
                <!-- <div class="col-md-2 mb-2">
                    <input type="date" name="from" class="form-control"
                        value="<?= htmlentities($from ?: date('Y-m-d', strtotime('-1 day'))) ?>">
                </div>
                <div class="col-md-2 mb-2">
                    <input type="date" name="to" class="form-control" value="<?= htmlentities($to ?: date('Y-m-d')) ?>">
                </div> -->
                <div class="col-md-5 mb-2">
                    <button type="submit" name="status" value="returned"
                        class="btn btn-outline-success btn-block status-btn <?= $status == 'returned' ? 'active' : '' ?>">
                        <i class="fa fa-check"></i> Returned Books
                    </button>
                </div>

                <div class="col-md-5 mb-2">
                    <button type="submit" name="status" value="notreturned"
                        class="btn btn-outline-danger btn-block status-btn <?= $status == 'notreturned' ? 'active' : '' ?>">
                        <i class="fa fa-exclamation-triangle"></i> Not Returned Books
                    </button>
                </div>

            </form>

            <!-- Issued Books Table -->
            <div class="card square-card mb-5">
                <div class="card-header bg-secondary text-white">
                    <i class="fa fa-book mr-2"></i> Issued Books List
                </div>
                <div class="card-body table-wrapper">
                    <table id="issuedBooksTable" class="table table-bordered table-hover table-sm text-dark">
                        <thead class="table-theme-header">
                            <tr>
                                <th>#</th>
                                <th>Book</th>
                                <th>Copy No</th>
                                <th>ACC No</th>
                                <th>Issued</th>
                                <th>Due</th>
                                <!-- <th>Extension Due</th> -->
                                <th>Return</th>
                                <th>Status</th>
                                <th>Action</th>
                                <th>Fine</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php
                            $sql = "SELECT ib.id as rid, ib.BookId, ib.CopyId, ib.IssuesDate, ib.DueDate, ib.ReturnDate, ib.fine,
               b.BookName, bc.accession_no, bc.book_no, ext.approved_due_date,
               (SELECT status FROM tblbook_extensions WHERE issue_id=ib.id ORDER BY id DESC LIMIT 1) as last_ext_status,
               (SELECT COUNT(*) FROM tblbook_extensions WHERE issue_id=ib.id AND requested_by=:bid) as extCount
        FROM tblissuedbookdetails ib
        JOIN tblbooks b ON b.id = ib.BookId
        LEFT JOIN tblbookcopies bc ON bc.id = ib.CopyId
        LEFT JOIN tblbook_extensions ext ON ext.issue_id = ib.id
        WHERE ib.BorrowerID=:bid AND ib.BorrowerType='staff'";
                            //                     $sql = "SELECT ib.id as rid, ib.BookId, ib.CopyId, ib.IssuesDate, ib.DueDate, ib.ReturnDate, ib.fine,
                            //        b.BookName, b.ISBNNumber, bc.book_no,
                            //        (SELECT requested_due_date FROM tblbook_extensions WHERE issue_id=ib.id AND status='Approved' ORDER BY id DESC LIMIT 1) as approved_due_date,
                            //        (SELECT status FROM tblbook_extensions WHERE issue_id=ib.id ORDER BY id DESC LIMIT 1) as last_ext_status,
                            //        (SELECT COUNT(*) FROM tblbook_extensions WHERE issue_id=ib.id AND requested_by=:bid) as extCount
                            // FROM tblissuedbookdetails ib
                            // JOIN tblbooks b ON b.id = ib.BookId
                            // LEFT JOIN tblbookcopies bc ON bc.id = ib.CopyId
                            // WHERE ib.BorrowerID=:bid AND ib.BorrowerType='student'";
                            
                            if ($bookname)
                                $sql .= " AND b.BookName LIKE :bookname";
                            if ($from)
                                $sql .= " AND DATE(ib.IssuesDate) >= :from";
                            if ($to)
                                $sql .= " AND DATE(ib.IssuesDate) <= :to";
                            if ($status == 'returned')
                                $sql .= " AND ib.ReturnDate IS NOT NULL";
                            elseif ($status == 'notreturned')
                                $sql .= " AND ib.ReturnDate IS NULL";

                            $sql .= " ORDER BY ib.id DESC";

                            $query = $dbh->prepare($sql);
                            $query->bindParam(':bid', $borrowerId, PDO::PARAM_STR);
                            if ($bookname) {
                                $bk = "%$bookname%";
                                $query->bindParam(':bookname', $bk, PDO::PARAM_STR);
                            }
                            // if ($from)
                            //     $query->bindParam(':from', $from, PDO::PARAM_STR);
                            // if ($to)
                            //     $query->bindParam(':to', $to, PDO::PARAM_STR);
                            $query->execute();
                            $results = $query->fetchAll(PDO::FETCH_OBJ);

                            $cnt = 1;
                            $todayDT = new DateTime('today');

                            if ($results) {
                                foreach ($results as $row) {
                                    $normalDue = $row->DueDate ? (new DateTime($row->DueDate))->setTime(0, 0, 0) : null;
                                    $extDue = $row->approved_due_date ? (new DateTime($row->approved_due_date))->setTime(0, 0, 0) : null;
                                    $finalDue = $extDue ?? $normalDue;

                                    $displayFine = (float) ($row->fine ?? 0);
                                    if (empty($row->ReturnDate) && $finalDue && $todayDT > $finalDue) {
                                        $displayFine = compute_fine_amount($dbh, (int) $row->rid, $finalDue->format('Y-m-d'));
                                    }

                                    if (!empty($row->ReturnDate)) {
                                        $status = "<span class='badge badge-success'>Returned</span>";
                                    } else {
                                        $isExt = !empty($row->approved_due_date);
                                        if ($row->last_ext_status === 'Cancelled')
                                            $status = "<span class='badge badge-dark'>Extension Cancelled</span>";
                                        elseif ($finalDue && $todayDT->format('Y-m-d') === $finalDue->format('Y-m-d')) {
                                            $status = $isExt ? "<span class='badge badge-info'>Extended Due Today</span>" : "<span class='badge badge-info'>Due Today</span>";
                                        } elseif ($finalDue && $todayDT < $finalDue && $todayDT->diff($finalDue)->days <= 2) {
                                            $status = $isExt ? "<span class='badge badge-warning'>Extended Due Soon</span>" : "<span class='badge badge-warning'>Due Soon</span>";
                                        } elseif ($finalDue && $todayDT > $finalDue) {
                                            $status = $isExt ? "<span class='badge badge-danger'>Extended Overdue</span>" : "<span class='badge badge-danger'>Overdue</span>";
                                        } else {
                                            $status = $isExt ? "<span class='badge badge-secondary'>Extended</span>" : "<span class='badge badge-secondary'>Not Returned</span>";
                                        }
                                    }
                                    ?>
                                    <tr>
                                        <td><?= $cnt++; ?></td>
                                        <td><?= htmlentities($row->BookName); ?></td>
                                        <td><?= htmlentities($row->book_no ?? '-'); ?></td>
                                        <td><?= htmlentities($row->accession_no); ?></td>
                                        <td>
                                            <?php
                                            $date = new DateTime($row->IssuesDate);
                                            echo $date->format('d-m-Y | h:i A');
                                            ?>
                                        </td>

                                        <td class="no-wrap fw-bold">
                                            <?= !empty($row->approved_due_date)
                                                ? (new DateTime($row->approved_due_date))->format('d-M-Y')
                                                : (new DateTime($row->DueDate))->format('d-M-Y'); ?>
                                        </td>

                                        <!-- <td><?= $row->approved_due_date ? htmlentities($row->approved_due_date) : '-'; ?></td> -->
                                        <td><?= $row->ReturnDate ? htmlentities($row->ReturnDate) : "<span class='text-danger'>Not Returned</span>"; ?>
                                        </td>
                                        <td><?= $status; ?></td>
                                        <td>
                                            <?php
                                            if ($row->ReturnDate) {
                                                echo "-";
                                            } elseif ($row->last_ext_status === 'Pending') {
                                                echo "<span class='badge badge-warning'>Extension Pending</span>";
                                            } elseif ($row->last_ext_status === 'Approved') {
                                                echo "<span class='badge badge-success'>Extension Approved</span>";
                                            } elseif ($row->last_ext_status === 'Rejected') {
                                                echo "<span class='badge badge-danger'>Extension Rejected</span>";
                                            } elseif ($row->last_ext_status === 'Cancelled') {
                                                echo "<span class='badge badge-dark'>Extension Cancelled</span>";
                                            } else {
                                                if ($row->extCount < 2) {
                                                    $currentDueStr = $row->approved_due_date ?: $row->DueDate;
                                                    $allowRequest = false;
                                                    if ($currentDueStr) {
                                                        $currentDue = (new DateTime($currentDueStr))->setTime(0, 0, 0);
                                                        if ($todayDT <= $currentDue)
                                                            $allowRequest = true;
                                                    }
                                                    if ($allowRequest) {
                                                        echo "<button class='btn btn-sm btn-primary requestExtBtn' data-issue='{$row->rid}'><i class='fa fa-clock'></i> Request Extension</button>";
                                                    } else {
                                                        echo "<span class='text-muted small'>No Extension Allowed</span>";
                                                    }
                                                } else {
                                                    echo "<span class='text-muted'>Limit Reached</span>";
                                                }
                                            }
                                            ?>
                                        </td>
                                        <td class="fw-bold text-danger">
                                            <?= $displayFine > 0 ? "₹" . number_format($displayFine, 2) : "-"; ?>
                                        </td>
                                    </tr>
                                    <?php
                                }
                            } else {
                                echo "<tr><td></td><td class='text-center text-muted'>No records found.</td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>";
                            }
                            ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <!-- Extension Modal -->
        <div class="modal fade" id="extModal" tabindex="-1">
            <div class="modal-dialog">
                <form method="post" class="modal-content">
                    <div class="modal-header bg-primary text-white">
                        <h5 class="modal-title">Request Extension</h5>
                        <button type="button" class="close text-white" data-dismiss="modal">&times;</button>
                    </div>
                    <div class="modal-body">
                        <input type="hidden" name="issue_id" id="extIssueId">
                        <div class="form-group">
                            <label>How many days do you want?</label>
                            <input type="number" name="days" min="1" class="form-control" required>
                            <small class="text-muted">Max 2 extension requests allowed per book.</small>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="submit" name="request_extension" class="btn btn-success">Submit</button>
                    </div>
                </form>
            </div>
        </div>

        <?php include('includes/footer.php'); ?>
    </div>

    <script src="https://code.jquery.com/jquery-3.7.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.6/js/dataTables.bootstrap4.min.js"></script>
    <script src="https://cdn.datatables.net/buttons/2.4.1/js/dataTables.buttons.min.js"></script>
    <script src="https://cdn.datatables.net/buttons/2.4.1/js/buttons.bootstrap4.min.js"></script>
    <script src="https://cdn.datatables.net/buttons/2.4.1/js/buttons.html5.min.js"></script>
    <script src="https://cdn.datatables.net/buttons/2.4.1/js/buttons.print.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.1.3/jszip.min.js"></script>
    <script>
        $(function () {
            $('#issuedBooksTable').DataTable({
                // dom: 'Bfrtip',
                // buttons: [
                //     { extend: 'print', className: 'btn btn-info', text: '<i class="fa fa-print"></i> Print' },
                //     { extend: 'excelHtml5', className: 'btn btn-success', text: '<i class="fa fa-file-excel"></i> Excel' }
                // ],
                pageLength: 10
            });

            $(document).on("click", ".requestExtBtn", function () {
                let issueId = $(this).data("issue");
                $("#extIssueId").val(issueId);
                $("#extModal").modal("show");
            });
        });
    </script>
</body>

</html>