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

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

// Filters
$category = $_GET['category'] ?? '';
$rack = $_GET['rack'] ?? '';
$author = $_GET['author'] ?? '';
$department = $_GET['department'] ?? '';
$degree = $_GET['degree'] ?? '';
?>
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>Damaged Book Copies Report | 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']; ?>">

  <!-- Bootstrap -->
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css" rel="stylesheet">
  <!-- DataTables -->
  <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">
  <!-- FontAwesome -->
  <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
  <!-- Select2 -->
  <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />

  <style>
    .square-card {
      background-color: #fff;
      border: 1px solid #dee2e6;
      border-radius: 6px;
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
    }

    .header-line {
      font-size: 22px;
      font-weight: 600;
      color: #d52222;
    }

    .main-content {
      margin-left: 180px;
      margin-top: 50px;
      padding: 20px;
    }

    /* Make all "No ..." options red */
    .form-control option[value^="no"] {
      color: red;
      font-weight: bold;
    }

    .badge {
      font-size: 13px;
      padding: 6px 10px;
      border-radius: 6px;
    }

    .deleted-item {
      opacity: 0.6;
      /* faded effect */
      color: #6c757d !important;
      /* muted gray text */
    }

    .deleted-label {
      font-size: 12px;
      color: #dc3545;
      /* subtle red */
      font-style: italic;
      margin-left: 4px;
    }
  </style>
</head>

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

    <div class="main-content flex-grow-1">
      <div class="row mb-4">
        <div class="col-md-12 d-flex justify-content-between align-items-center">
          <h5 class="header-line" style="font-size:20px;">
            <i class="fa fa-exclamation-triangle mr-2"></i> DAMAGED BOOK COPIES REPORT
          </h5>
        </div>
      </div>

      <!-- Filters -->
      <form method="get" class="row mb-3">
        <div class="col-md-2">
          <select name="category" id="category" class="form-control select2-ajax" data-placeholder="Search Category">
            <?php if ($category): ?>
              <?php
              $stmt = $dbh->prepare("SELECT CategoryName FROM tblcategory WHERE id=:id");
              $stmt->bindParam(':id', $category, PDO::PARAM_INT);
              $stmt->execute();
              $cat = $stmt->fetch(PDO::FETCH_ASSOC);
              ?>
              <option value="<?= $category ?>" selected><?= htmlentities($cat['CategoryName'] ?? 'No Category') ?>
              </option>
            <?php endif; ?>
          </select>
        </div>

        <div class="col-md-2">
          <select name="rack" id="rack" class="form-control select2-ajax" data-placeholder="Search Rack">
            <?php if ($rack): ?>
              <?php
              $stmt = $dbh->prepare("SELECT rack_no FROM tbl_racks WHERE id=:id");
              $stmt->bindParam(':id', $rack, PDO::PARAM_INT);
              $stmt->execute();
              $rk = $stmt->fetch(PDO::FETCH_ASSOC);
              ?>
              <option value="<?= $rack ?>" selected><?= htmlentities($rk['rack_no'] ?? 'No rack') ?></option>
            <?php endif; ?>
          </select>
        </div>

        <div class="col-md-2">
          <select name="author" id="author" class="form-control select2-ajax" data-placeholder="Search Author">
            <?php if ($author): ?>
              <?php
              $stmt = $dbh->prepare("SELECT AuthorName FROM tblauthors WHERE id=:id");
              $stmt->bindParam(':id', $author, PDO::PARAM_INT);
              $stmt->execute();
              $auth = $stmt->fetch(PDO::FETCH_ASSOC);
              ?>
              <option value="<?= $author ?>" selected><?= htmlentities($auth['AuthorName'] ?? 'No Author') ?></option>
            <?php endif; ?>
          </select>
        </div>

        <div class="col-md-2">
          <select name="department" id="department" class="form-control select2-ajax"
            data-placeholder="Search Department">
            <?php if ($department): ?>
              <?php
              $stmt = $dbh->prepare("SELECT department_name FROM tbldepartment WHERE department_id=:id");
              $stmt->bindParam(':id', $department, PDO::PARAM_INT);
              $stmt->execute();
              $dept = $stmt->fetch(PDO::FETCH_ASSOC);
              ?>
              <option value="<?= $department ?>" selected><?= htmlentities($dept['department_name'] ?? 'No Department') ?>
              </option>
            <?php endif; ?>
          </select>
        </div>

        <div class="col-md-2">
          <select name="degree" id="degree" class="form-control select2-ajax" data-placeholder="Search Degree">
            <?php if ($degree): ?>
              <?php
              $stmt = $dbh->prepare("SELECT degree_name FROM tbldegree WHERE degree_id=:id");
              $stmt->bindParam(':id', $degree, PDO::PARAM_INT);
              $stmt->execute();
              $deg = $stmt->fetch(PDO::FETCH_ASSOC);
              ?>
              <option value="<?= $degree ?>" selected><?= htmlentities($deg['degree_name'] ?? 'No Degree') ?></option>
            <?php endif; ?>
          </select>
        </div>

        <div class="col-md-2 mt-2">
          <button class="btn btn-danger btn-block"><i class="fa fa-filter"></i> Apply</button>
        </div>
      </form>

      <!-- Table -->
      <div class="card square-card">
        <div class="card-body table-responsive">
          <table id="copiesTable" class="table table-bordered table-striped">
            <thead class="table-theme-header">
              <tr>
                <th>#</th>
                <th>Book Name</th>
                <!-- <th>Edition</th>
                <th>Volume</th> -->
                <!-- <th>Publisher</th> -->
                <!-- <th>Publication Year</th>
                <th>ISBN</th> -->
                <th>Accession No</th>
                <th>Copy No</th>
                <th>Status</th>
                <th>Category</th>
                <th>Rack</th>
                <th>Authors</th>
                <th>Department</th>
                <th>Degree</th>
                <th>QRCode</th>
              </tr>
            </thead>
            <tbody>
              <?php
              $sql = "SELECT c.id, c.book_no, c.book_status, c.QRCode,
                         b.BookName,  b.ISBNNumber, c.accession_no, b.Edition, b.Volume,
                         b.Publisher, b.PublicationYear, b.AuthorIds,
                         cat.is_deleted AS catdel, cat.CategoryName, r.rack_no,
                        d.is_deleted AS deptdel, d.department_name,
                        dg.is_deleted AS degreedel, dg.degree_name
                  FROM tblbookcopies c
                  JOIN tblbooks b ON b.id=c.book_id
                  LEFT JOIN tblcategory cat ON cat.id=b.CatId
                  LEFT JOIN tbl_racks r ON r.id=b.rack_id
                  LEFT JOIN tbldepartment d ON d.department_id=b.department_id
                  LEFT JOIN tbldegree dg ON dg.degree_id=b.degree_id
                  WHERE c.book_status='damaged'";

              // Apply filters
              if ($category == 'nocat')
                $sql .= " AND b.CatId IS NULL";
              elseif ($category != '')
                $sql .= " AND b.CatId=:cat";

              if ($rack == 'norack')
                $sql .= " AND b.rack_id IS NULL";
              elseif ($rack != '')
                $sql .= " AND b.rack_id=:rack";

              if ($author == 'noauthor')
                $sql .= " AND b.AuthorIds IS NULL";
              elseif ($author != '')
                $sql .= " AND FIND_IN_SET(:author, b.AuthorIds)";

              if ($department == 'nodept')
                $sql .= " AND b.department_id IS NULL";
              elseif ($department != '')
                $sql .= " AND b.department_id=:dept";

              if ($degree == 'nodegree')
                $sql .= " AND b.degree_id IS NULL";
              elseif ($degree != '')
                $sql .= " AND b.degree_id=:degree";

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

              $query = $dbh->prepare($sql);

              if ($category != '' && $category != 'nocat')
                $query->bindParam(':cat', $category, PDO::PARAM_INT);
              if ($rack != '' && $rack != 'norack')
                $query->bindParam(':rack', $rack, PDO::PARAM_INT);
              if ($author != '' && $author != 'noauthor')
                $query->bindParam(':author', $author, PDO::PARAM_INT);
              if ($department != '' && $department != 'nodept')
                $query->bindParam(':dept', $department, PDO::PARAM_INT);
              if ($degree != '' && $degree != 'nodegree')
                $query->bindParam(':degree', $degree, PDO::PARAM_INT);

              $query->execute();
              $results = $query->fetchAll(PDO::FETCH_OBJ);
              $cnt = 1;

              foreach ($results as $row):
                ?>
                <tr>
                  <td><?= $cnt++ ?></td>
                  <td><?= htmlentities($row->BookName) ?></td>
                  <!-- <td><?= htmlentities($row->Edition ?? '-') ?></td>
                  <td><?= htmlentities($row->Volume ?? '-') ?></td> -->
                  <!-- <td><?= htmlentities($row->Publisher ?? '-') ?></td> -->
                  <!-- <td><?= htmlentities($row->PublicationYear ?? '-') ?></td> -->
                  <!-- <td><?= htmlentities($row->ISBNNumber ?? '-') ?></td> -->
                  <td><?= htmlentities($row->accession_no ?? '-') ?></td>
                  <td><?= htmlentities($row->book_no ?? '-') ?></td>
                  <td><span class="badge badge-danger">Damaged</span></td>
                  <!-- <td><?= $row->CategoryName ?? "<span class='text-muted'>No Category</span>" ?></td> -->
                  <td>
                    <?php if ($row->catdel == 1): ?>
                      <span class="deleted-item"><?= htmlentities($row->CategoryName) ?></span>
                      <span class="deleted-label">(Deleted)</span>
                    <?php else: ?>
                      <?= $row->CategoryName ?? "<span class='text-muted'>No Category</span>" ?>
                    <?php endif; ?>
                  </td>
                  <td><?= $row->rack_no ?? "<span class='text-muted'>No Rack</span>" ?></td>
                  <!-- <td>
                    <?= $authorNames ? htmlentities(implode(', ', $authorNames)) : "<span class='text-muted'>No Author</span>" ?>
                  </td> -->
                  <td>
                    <?php
                    $authorsList = [];
                    if (!empty($row->AuthorIds)) {
                      $stmt = $dbh->query("SELECT AuthorName, is_deleted FROM tblauthors WHERE id IN (" . $row->AuthorIds . ")");
                      $authors = $stmt->fetchAll(PDO::FETCH_ASSOC);

                      foreach ($authors as $a) {
                        $name = htmlentities($a['AuthorName']);
                        if (isset($a['is_deleted']) && $a['is_deleted'] == 1) {
                          $authorsList[] = "<span class='deleted-item'>$name</span><span class='deleted-label'>(Deleted)</span>";
                        } else {
                          $authorsList[] = $name;
                        }
                      }
                    }
                    echo !empty($authorsList)
                      ? implode(", ", $authorsList)
                      : "<span class='text-muted'>No Author</span>";
                    ?>
                  </td>
                  <td>
                    <?php if ($row->deptdel == 1): ?>
                      <span class="deleted-item"><?= htmlentities($row->department_name) ?></span>
                      <span class="deleted-label">(Deleted)</span>
                    <?php else: ?>
                      <?= $row->department_name ?? "<span class='text-muted'>No Department</span>" ?>
                    <?php endif; ?>
                  </td>
                  <td>
                    <?php if ($row->degreedel == 1): ?>
                      <span class="deleted-item"><?= htmlentities($row->degree_name) ?></span>
                      <span class="deleted-label">(Deleted)</span>
                    <?php else: ?>
                      <?= $row->degree_name ?? "<span class='text-muted'>No Degree</span>" ?>
                    <?php endif; ?>
                  </td>
                  <td>
                    <?php if ($row->QRCode): ?>
                      <img src="../<?= htmlentities($row->QRCode) ?>" width="40">
                    <?php else: ?>
                      <span class='text-muted'>No QR</span>
                    <?php endif; ?>
                  </td>
                </tr>
              <?php endforeach; ?>
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </div>

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

  <!-- Scripts -->
  <script src="https://code.jquery.com/jquery-3.6.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 src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>

  <script>
    $(document).ready(function () {
      $('#copiesTable').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,
        ordering: true
      });

      // Initialize Select2 for dropdowns
      $('.select2-ajax').each(function () {
        let select = $(this);
        let type = select.attr('id');
        select.select2({
          placeholder: select.data('placeholder'),
          ajax: {
            url: 'get_options.php',
            dataType: 'json',
            delay: 250,
            data: function (params) {
              return { q: params.term, type: type };
            },
            processResults: function (data) {
              return { results: data };
            },
            cache: true
          },
          allowClear: true,
          templateResult: function (option) {
            if (!option.id) return option.text;
            const noValues = ['nocat', 'norack', 'noauthor', 'nodept', 'nodegree'];
            if (noValues.includes(option.id)) {
              return $('<span style="color:red; font-weight:bold;">' + option.text + '</span>');
            }
            return $('<span>' + option.text + '</span>');
          },
          templateSelection: function (option) {
            const noValues = ['nocat', 'norack', 'noauthor', 'nodept', 'nodegree'];
            if (option.id && noValues.includes(option.id)) {
              return $('<span style="color:red; font-weight:bold;">' + option.text + '</span>');
            }
            return option.text || option.text;
          }
        });
      });
    });
  </script>
</body>

</html>