<?php
session_start();
error_reporting(0);
include('includes/config.php');
date_default_timezone_set('Asia/Kolkata');
$updatetime = date('Y-m-d H:i:s');
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
if (strlen($_SESSION['alogin']) == 0) {
  header('location:index.php');
  exit;
}

// --- Handle Actions ---
if (isset($_POST['action'])) {
  $extId = intval($_POST['ext_id']);
  $admin = $_SESSION['alogin'];

  if ($_POST['action'] == 'approve') {
    $newDue = $_POST['new_due_date'];
    $remark = !empty($_POST['remark']) ? $_POST['remark'] : null;

    $sql = "UPDATE tblbook_extensions 
                   SET status='Approved', 
                       approved_due_date=:newdue, 
                       admin_remark=:remark,
                       approved_by=:admin,
                       decision_date=:updatetime 
                 WHERE id=:id";
    $q = $dbh->prepare($sql);
    $q->execute([
      ':newdue' => $newDue,
      ':remark' => $remark,
      ':admin' => $admin,
      ':id' => $extId,
      ':updatetime' => $updatetime
    ]);
    $_SESSION['msg'] = "✅ Extension approved.";
  } elseif ($_POST['action'] == 'reject') {
    $remark = $_POST['remark'];
    $sql = "UPDATE tblbook_extensions 
                   SET status='Rejected', 
                       admin_remark=:r, 
                       approved_by=:admin,
                       decision_date=:updatetime 
                 WHERE id=:id";
    $q = $dbh->prepare($sql);
    $q->execute([':r' => $remark, ':admin' => $admin, ':id' => $extId, ':updatetime' => $updatetime]);
    $_SESSION['msg'] = "❌ Extension rejected.";
  }
  header("Location: extension-requests.php");
  exit;
}

// --- Fetch Requests ---
// $sql = "SELECT e.*, 
//                i.BookId, i.DueDate as currentDueDate, b.BookName, bc.book_no, 
//                s.FullName, s.StudentId
//         FROM tblbook_extensions e
//         JOIN tblissuedbookdetails i ON e.issue_id=i.id
//         JOIN tblbooks b ON b.id=i.BookId
//         LEFT JOIN tblbookcopies bc ON bc.id=i.CopyId
//         JOIN tblstudents s ON s.StudentId=e.requested_by
//         ORDER BY e.id DESC";
$sql = "SELECT e.*, 
               i.BookId, 
               i.DueDate AS currentDueDate, 
               b.BookName, 
               bc.book_no,

               -- Student details
               s.FullName AS student_name,
               s.StudentId AS student_id,

               -- Staff details
               st.FullName AS staff_name,
               st.StaffId AS staff_id

        FROM tblbook_extensions e
        JOIN tblissuedbookdetails i ON e.issue_id = i.id
        JOIN tblbooks b ON b.id = i.BookId
        LEFT JOIN tblbookcopies bc ON bc.id = i.CopyId

        LEFT JOIN tblstudents s 
               ON e.requested_by = s.StudentId 
              AND e.requested_type = 'student'

        LEFT JOIN tblstaff st 
               ON e.requested_by = st.StaffId 
              AND e.requested_type = 'staff'

        ORDER BY e.id DESC";

$query = $dbh->prepare($sql);
$query->execute();
$results = $query->fetchAll(PDO::FETCH_OBJ);
?>
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8" />
  <title>Extension Requests | Admin</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;
    }

    .dataTables_filter label {
      color: #000 !important;
      font-weight: 500;
    }

    .dataTables_filter input {
      height: 32px;
      font-size: 0.95rem;
      padding: 4px 8px;
    }
  </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 mb-4">
        <div class="col-md-12">
            <h5 class="header-line"><i class="fa fa-clock mr-2"></i>BOOK EXTENSION REQUESTS</h5>
        </div>
    </div> -->
    <div class="main-content flex-grow-1">
      <div class="row pad-botm mb-4">
        <div class="col-md-12">
          <h5 class="header-line" style="color:#0d6efd;"><i class="fa fa-clock mr-2"></i>BOOK EXTENSION REQUESTS</h5>
        </div>
      </div>

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

      <div class="card square-card mb-5">
        <div class="card-header bg-secondary text-white">
          <i class="fa fa-book mr-2"></i> Extension Requests List
        </div>
        <div class="card-body table-wrapper">
          <table id="extTable" class="table table-bordered table-hover table-sm text-dark">
            <thead class="table-theme-header">
              <tr>
                <th>#</th>
                <th>Borrower</th>
                <th>Student</th>
                <th>Book</th>
                <th>Copy No</th>
                <th>Current Due</th>
                <th>Requested +Days</th>
                <th>Requested Due</th>
                <th>Approved Due</th>
                <th>Status</th>
                <th>Times Extended</th>
                <th>Action / Remarks</th>
              </tr>
            </thead>
            <tbody>
              <?php
              $cnt = 1;
              foreach ($results as $row):
                $chk = $dbh->prepare("SELECT COUNT(*) FROM tblbook_extensions WHERE issue_id=:iid AND status='Approved'");
                $chk->execute([':iid' => $row->issue_id]);
                $extCount = $chk->fetchColumn();
                ?>
                <tr>
                  <td><?= $cnt++; ?></td>
                  <td><?= $row->requested_type ?></td>
                  <td>
                    <?php
                    if ($row->requested_type == 'student') {
                      echo htmlentities($row->student_name) . " (STU - " . $row->student_id . ")";
                    } elseif ($row->requested_type == 'staff') {
                      echo htmlentities($row->staff_name) . " (STAFF - " . $row->staff_id . ")";
                    }
                    ?>
                  </td>
                  <td><?= htmlentities($row->BookName); ?></td>
                  <td><?= htmlentities($row->book_no ?? '-'); ?></td>
                  <td><?= htmlentities($row->currentDueDate); ?></td>
                  <td><?= htmlentities($row->requested_days); ?> days</td>
                  <td><?= htmlentities($row->requested_due_date); ?></td>
                  <td><?= htmlentities($row->approved_due_date ?? '-'); ?></td>
                  <td>
                    <?php
                    if ($row->status == 'Pending')
                      echo "<span class='badge badge-warning'>Pending</span>";
                    elseif ($row->status == 'Approved')
                      echo "<span class='badge badge-success'>Approved</span>";
                    elseif ($row->status == 'Rejected')
                      echo "<span class='badge badge-danger'>Rejected</span>";
                    elseif ($row->status == 'Auto-Cancelled')
                      echo "<span class='badge badge-secondary'>Auto-Cancelled</span>";
                    ?>
                  </td>
                  <td><?= $extCount; ?></td>
                  <td>
                    <?php if ($row->status == 'Pending'): ?>
                      <button class="btn btn-sm btn-success approveBtn" data-id="<?= $row->id ?>"
                        data-due="<?= $row->requested_due_date ?>">Accept</button>
                      <button class="btn btn-sm btn-danger rejectBtn" data-id="<?= $row->id ?>">Reject</button>
                    <?php else: ?>
                      <small><strong>Remark:</strong> <?= htmlentities($row->admin_remark ?? '-'); ?><br>
                        <strong>By:</strong> <?= htmlentities($row->approved_by ?? '-'); ?><br>
                        <strong>On:</strong> <?= htmlentities($row->decision_date ?? '-'); ?></small>
                    <?php endif; ?>
                  </td>
                </tr>
              <?php endforeach; ?>
            </tbody>
          </table>
        </div>
      </div>

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

  <!-- Approve Modal -->
  <div class="modal fade" id="approveModal" tabindex="-1">
    <div class="modal-dialog">
      <form method="post" class="modal-content">
        <div class="modal-header bg-success text-white">
          <h5 class="modal-title">Approve Extension</h5>
          <button type="button" class="close text-white" data-dismiss="modal">&times;</button>
        </div>
        <div class="modal-body">
          <input type="hidden" name="ext_id" id="approveExtId">
          <div class="form-group">
            <label>New Due Date</label>
            <input type="date" name="new_due_date" id="approveDueDate" class="form-control" required>
          </div>
          <div class="form-group">
            <label>Remarks (Optional)</label>
            <textarea name="remark" class="form-control"></textarea>
          </div>
        </div>
        <div class="modal-footer">
          <button type="submit" name="action" value="approve" class="btn btn-success">Confirm</button>
        </div>
      </form>
    </div>
  </div>

  <!-- Reject Modal -->
  <div class="modal fade" id="rejectModal" tabindex="-1">
    <div class="modal-dialog">
      <form method="post" class="modal-content">
        <div class="modal-header bg-danger text-white">
          <h5 class="modal-title">Reject Extension</h5>
          <button type="button" class="close text-white" data-dismiss="modal">&times;</button>
        </div>
        <div class="modal-body">
          <input type="hidden" name="ext_id" id="rejectExtId">
          <div class="form-group">
            <label>Remarks</label>
            <textarea name="remark" class="form-control" required></textarea>
          </div>
        </div>
        <div class="modal-footer">
          <button type="submit" name="action" value="reject" class="btn btn-danger">Reject</button>
        </div>
      </form>
    </div>
  </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>
    $(function () {
      $('#extTable').DataTable({
        pageLength: 10,
        responsive: true,
        ordering: true
      });

      $(".approveBtn").click(function () {
        let id = $(this).data("id");
        let due = $(this).data("due");
        $("#approveExtId").val(id);
        $("#approveDueDate").val(due);
        $("#approveModal").modal("show");
      });

      $(".rejectBtn").click(function () {
        let id = $(this).data("id");
        $("#rejectExtId").val(id);
        $("#rejectModal").modal("show");
      });
    });
  </script>
</body>

</html>