<?php
session_start();
// ini_set('display_errors', 1);
// ini_set('display_startup_errors', 1);
error_reporting(0);
include('includes/config.php');

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

// Filters
$userType = $_GET['usertype'] ?? ''; // all, student, staff

// If no dates given, default to today
$fromDate = !empty($_GET['from']) ? $_GET['from'] : date('Y-m-d\T8:00');
$toDate = !empty($_GET['to']) ? $_GET['to'] : date('Y-m-d\T20:00');

// Convert to proper MySQL datetime format
$fromDateTime = date('Y-m-d H:i:s', strtotime($fromDate));
$toDateTime = date('Y-m-d H:i:s', strtotime($toDate));

// Build queries
$sqlParts = [];

if ($userType == '' || $userType == 'student') {
  $sqlParts[] = "SELECT l.id, 'Student' as user_type, s.FullName as name, s.Photo as photo, 
                        s.passed_out_year, s.MobileNumber, l.loginTime, l.logoutTime
                 FROM tblstudentlogs l
                 JOIN tblstudents s ON s.id = l.StudentId
                 WHERE l.loginTime BETWEEN :from AND :to";
}

if ($userType == '' || $userType == 'staff') {
  $sqlParts[] = "SELECT l.id, 'Staff' as user_type, st.FullName as name, st.Photo as photo,
                        NULL as passed_out_year, st.MobileNumber, l.loginTime, l.logoutTime
                 FROM tblstafflogs l
                 JOIN tblstaff st ON st.id = l.StaffId
                 WHERE l.loginTime BETWEEN :from AND :to";
}

$sql = implode(" UNION ALL ", $sqlParts) . " ORDER BY loginTime DESC";

$query = $dbh->prepare($sql);
$query->bindParam(':from', $fromDateTime);
$query->bindParam(':to', $toDateTime);

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

?>


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

<head>
  <meta charset="UTF-8">
  <title>Login Logs 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">
  <!-- Flatpicker CSS -->
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">


  <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: #0056b3;
    }

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

    .user-photo {
      width: 40px;
      height: 40px;
      border-radius: 50%;
      object-fit: cover;
    }

    .badge-student {
      background-color: #28a745;
      /* green */
      color: #fff;
    }

    .badge-staff {
      background-color: #007bff;
      /* blue */
      color: #fff;
    }
  </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 pad-botm mb-4">
        <div class="col-md-12 d-flex justify-content-between align-items-center">
          <h5 class="header-line" style="color:#0d6efd; font-size:20px;"><i class="fa fa-history mr-2"></i> LOGS REPORT</h5>
        </div>
      </div>

      <!-- Filters -->
      <form method="get" class="row mb-4">
        <div class="col-md-3">
          <select name="usertype" class="form-control">
            <option value="">All</option>
            <option value="student" <?= $userType == 'student' ? 'selected' : '' ?>>Students</option>
            <option value="staff" <?= $userType == 'staff' ? 'selected' : '' ?>>Staff</option>
          </select>
        </div>
        <div class="col-md-3">
          <input type="text" id="fromDate" name="from"
            value="<?= htmlentities(date('Y-m-d h:i A', strtotime($fromDateTime))) ?>" class="form-control">
        </div>
        <div class="col-md-3">
          <input type="text" id="toDate" name="to"
            value="<?= htmlentities(date('Y-m-d h:i A', strtotime($toDateTime))) ?>" class="form-control">
        </div>
        <div class="col-md-2">
          <button class="btn btn-primary btn-block"><i class="fa fa-filter"></i> Filter</button>
        </div>
      </form>

      <!-- Table -->
      <div class="card square-card">
        <div class="card-body table-responsive">
          <table id="logsTable" class="table table-bordered table-striped">
            <thead class="table-theme-header">
              <tr>
                <th>#</th>
                <th>User Type</th>
                <th>Name</th>
                <th>Photo</th>
                <th>Academic Year</th>
                <th>Mobile</th>
                <th>Login Time</th>
                <th>Logout Time</th>
              </tr>
            </thead>
            <tbody>
              <?php $cnt = 1;
              foreach ($results as $row): ?>
                <tr>
                  <td><?= $cnt++ ?></td>
                  <td>
                    <?php if ($row->user_type == 'Student') { ?>
                      <span class="badge badge-student"><?= $row->user_type ?></span>
                    <?php } else { ?>
                      <span class="badge badge-staff"><?= $row->user_type ?></span>
                    <?php } ?>
                  </td>
                  <td><?= htmlentities($row->name) ?></td>
                  <td>
                    <?php if ($row->photo): ?>
                      <?php if ($row->user_type == 'Student') { ?>
                        <img src="../<?= htmlentities($row->photo) ?>" class="user-photo">
                      <?php } else { ?>
                        <img src="../staff/<?= htmlentities($row->photo) ?>" class="user-photo">
                      <?php } ?>

                    <?php else: ?>
                      <span class="text-muted">No Photo</span>
                    <?php endif; ?>
                  </td>
                  <td><?= $row->passed_out_year ?? "<span class='text-muted'>-</span>" ?></td>
                  <td><?= htmlentities($row->MobileNumber) ?></td>
                  <td>
                    <?= $row->loginTime ? date("j-n-Y | g:i A", strtotime($row->loginTime)) : "-" ?>
                  </td>
                  <td>
                    <?= $row->logoutTime
                      ? date("j-n-Y | g:i A", strtotime($row->logoutTime))
                      : "<span class='badge badge-danger'>Active</span>" ?>
                  </td>

                  </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/flatpickr"></script>
  <script>
    flatpickr("#fromDate", {
      enableTime: true,
      dateFormat: "Y-m-d h:i K", // K shows AM/PM
      defaultDate: "<?= htmlentities(date('Y-m-d h:i A', strtotime($fromDateTime))) ?>"
    });

    flatpickr("#toDate", {
      enableTime: true,
      dateFormat: "Y-m-d h:i K",
      defaultDate: "<?= htmlentities(date('Y-m-d h:i A', strtotime($toDateTime))) ?>"
    });
  </script>
  <script>
    $(document).ready(function () {
      $('#logsTable').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
      });
    });
  </script>
</body>

</html>