<?php
date_default_timezone_set('Asia/Kolkata');
session_start();
error_reporting(0);
include('includes/config.php');
if (strlen($_SESSION['alogin']) == 0) {
  header('location:index.php');
} else { ?>
  <!-- HTML for admin dashboard with updated styling -->

  <!DOCTYPE html>
  <html xmlns="http://www.w3.org/1999/xhtml">

  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
    <link rel="icon" type="image/x-icon" href="../<?php echo $_SESSION['logo']; ?>">
    <meta name="description" content="" />
    <meta name="author" content="" />
    <title>Online Library Management System | Admin Dashboard</title>
    <link href="assets/css/bootstrap.css" rel="stylesheet" />
    <link href="assets/css/font-awesome.css" rel="stylesheet" />
    <!-- <link href="assets/css/style.css" rel="stylesheet" /> -->
    <link href='http://fonts.googleapis.com/css?family=Open+Sans' rel='stylesheet' type='text/css' />
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" />
  </head>
  <style>
    .main-content {
      margin-left: 180px;
      margin-top: 50px;
      padding: 20px;
    }

    .dashboard-wrapper {
      max-width: 1100px;
      margin: 30px auto;
      padding: 30px;
      background: linear-gradient(135deg, #f8f9fa, #e3f2fd);
      border-radius: 20px;
      box-shadow: 0 12px 30px rgba(0, 0, 0, 0.1);
    }

    .info-card {
      background-color: #ffffff;
      border-radius: 15px;
      box-shadow: 0 8px 20px rgba(0, 0, 0, 0.1);
      transition: 0.3s ease;
    }

    .info-card:hover {
      transform: translateY(-5px);
      box-shadow: 0 12px 30px rgba(0, 0, 0, 0.15);
    }

    .border-left-primary {
      border-left: 5px solid #007bff;
    }

    .border-left-danger {
      border-left: 5px solid #dc3545;
    }

    .info-card h6 {
      text-transform: uppercase;
      font-size: 14px;
      color: #555;
      margin-top: 10px;
    }

    .info-card h3 {
      font-size: 2rem;
      font-weight: 600;
      color: #333;
    }

    .col-md-12 h5 {
      color: #0d6efd;
      font-size: 20px;
    }

    @media (max-width: 768px) {
      #carousel-example {
        display: none;
      }
    }

    /* --- Hover Info Tooltip --- */
    .info-card {
      position: relative;
      overflow: hidden;
    }

    /* --- Hover Info Tooltip --- */
    .info-tooltip {
      position: absolute;
      bottom: -60px;
      left: 0;
      right: 0;
      background: #f8f9fa;
      color: #000;
      font-size: 13px;
      font-weight: 500;
      line-height: 1.4;
      opacity: 0;
      padding: 8px 12px;
      border-top: 1px solid #dee2e6;
      border-radius: 0 0 15px 15px;
      box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.05);
      transform: translateY(20px);
      transition: all 0.3s ease-in-out;
    }

    .info-card:hover .info-tooltip {
      opacity: 1;
      transform: translateY(0);
      bottom: 0;
    }


    /* --- Hover Arrow Animation --- */
    .info-card::after {
      content: '\f061';
      font-family: "Font Awesome 6 Free";
      font-weight: 900;
      color: #007bff;
      font-size: 18px;
      position: absolute;
      right: 20px;
      top: 40%;
      transform: translateY(-50%) translateX(15px);
      opacity: 0;
      transition: all 0.3s ease;
    }

    .info-card:hover::after {
      opacity: 1;
      transform: translateY(-50%) translateX(0);
    }
  </style>

  <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">
            <h5 class="header-line">ADMIN DASHBOARD</h5>
          </div>
          <!-- 🔹 Student Links Section -->
          <div class="row mt-3">
            <div class="col-md-3 text-center">
              <a href="../index.php" target="_blank" class="btn btn-primary btn-lg w-100">
                <i class="fa fa-sign-in-alt"></i> Student Login
              </a>
            </div>
            <div class="col-md-3 text-center">
              <a href="../signup.php" target="_blank" class="btn btn-success btn-lg w-100">
                <i class="fa fa-user-plus"></i> Student Signup
              </a>
            </div>
            <div class="col-md-3 text-center">
              <a href="../staff/index.php" target="_blank" class="btn btn-primary btn-lg w-100">
                <i class="fa fa-sign-in-alt"></i>Staff Login
              </a>
            </div>
            <div class="col-md-3 text-center">
              <a href="../staff/signup.php" target="_blank" class="btn btn-success btn-lg w-100">
                <i class="fa fa-user-plus"></i> Staff Signup
              </a>
            </div>
          </div>
          <!--  End Student Links Section -->
        </div>

        <!-- <div class="container dashboard-wrapper"> -->
        <?php
        $stats = [
          ["icon" => "fas fa-book", "query" => "SELECT id FROM tblbookcopies", "label" => "All Books", "class" => "info", "link" => "manage-books.php"],
          ["icon" => "fas fa-book-reader", "query" => "SELECT id FROM tblissuedbookdetails WHERE RetrunStatus=0", "label" => "Issued Books", "class" => "warning", "link" => "manage-issued-books.php"],
          ["icon" => "fas fa-exclamation-circle", "query" => "SELECT id FROM tblbook_extensions WHERE status='Pending'", "label" => "Extension Requests", "class" => "danger", "link" => "extension-requests.php"],
          ["icon" => "fas fa-user-tie", "query" => "SELECT id FROM tblstaff", "label" => "Staffs", "class" => "dark", "link" => "reg-staffs.php"],
          ["icon" => "fas fa-users", "query" => "SELECT id FROM tblstudents", "label" => "Students", "class" => "primary", "link" => "reg-students.php"],
          ["icon" => "fas fa-layer-group", "query" => "SELECT COUNT(*) FROM tbl_racks GROUP BY rack_no", "label" => "Cupboards", "class" => "secondary", "link" => "manage-racks.php"]
        ];

        foreach ($stats as $stat) {

          $tooltip = "";

          if ($stat['label'] == "All Books") {
            $query = $dbh->prepare("SELECT 
            SUM(book_status='available') as available,
            SUM(book_status='issued') as issued,
            SUM(book_status='lost') as lost,
            SUM(book_status='damaged') as damaged,
            SUM(book_status='NA') as notavailable
            FROM tblbookcopies");
            $query->execute();
            $result = $query->fetch(PDO::FETCH_ASSOC);
            $tooltip = "Available: {$result['available']} | Issued: {$result['issued']} | Lost: {$result['lost']} | Damaged: {$result['damaged']} | Not Available: {$result['notavailable']}";
          } elseif ($stat['label'] == "Students") {
            $query = $dbh->prepare("SELECT 
            SUM(Status=1) as active,
            SUM(Status=0) as pending,
            SUM(Status=2) as blocked
            FROM tblstudents");
            $query->execute();
            $result = $query->fetch(PDO::FETCH_ASSOC);
            $tooltip = "Active: {$result['active']} | Pending: {$result['pending']} | Blocked: {$result['blocked']}";
          } elseif ($stat['label'] == "Staffs") {
            $query = $dbh->prepare("SELECT 
            SUM(Status=1) as active,
            SUM(Status=0) as pending,
            SUM(Status=2) as blocked
            FROM tblstaff");
            $query->execute();
            $result = $query->fetch(PDO::FETCH_ASSOC);
            $tooltip = "Active: {$result['active']} | Pending: {$result['pending']} | Blocked: {$result['blocked']}";
          } elseif ($stat['label'] == "Extension Requests") {
            $query = $dbh->prepare("SELECT 
            SUM(status='Pending') as pending,
            SUM(status='Approved') as approved,
            SUM(status='Rejected') as rejected
            FROM tblbook_extensions");
            $query->execute();
            $result = $query->fetch(PDO::FETCH_ASSOC);
            $tooltip = "Pending: {$result['pending']} | Approved: {$result['approved']} | Rejected: {$result['rejected']}";
          } elseif ($stat['label'] == "Issued Books") {
            // Current date from PHP, not MySQL
            $today = new DateTime('now', new DateTimeZone('Asia/Kolkata'));

            // Fetch issued books with latest approved extension if any
            $query = $dbh->prepare("
        SELECT 
            ib.id AS issue_id, 
            ib.DueDate, 
            ib.RetrunStatus,
            be.approved_due_date
        FROM tblissuedbookdetails ib
        LEFT JOIN (
            SELECT e.issue_id, e.approved_due_date
            FROM tblbook_extensions e
            WHERE e.status = 'Approved'
            AND e.decision_date = (
                SELECT MAX(e2.decision_date)
                FROM tblbook_extensions e2 
                WHERE e2.issue_id = e.issue_id 
                AND e2.status = 'Approved'
            )
        ) be ON ib.id = be.issue_id
        WHERE ib.RetrunStatus = 0
    ");
            $query->execute();
            $rows = $query->fetchAll(PDO::FETCH_OBJ);

            // Counters
            $issued = 0;
            $overdue = 0;
            $extendedOverdue = 0;

            foreach ($rows as $row) {
              $issued++;

              // Determine which due date to consider (extended > normal)
              $dueDate = !empty($row->approved_due_date)
                ? new DateTime($row->approved_due_date)
                : new DateTime($row->DueDate);

              // Compare with current PHP date
              if ($today > $dueDate) {
                if (!empty($row->approved_due_date)) {
                  $extendedOverdue++;
                } else {
                  $overdue++;
                }
              }
            }

            // Tooltip text
            $tooltip = "
        <strong>Total Issued:</strong> {$issued} |
        <span style='color:#dc3545;'><strong>Overdue:</strong> {$overdue}</span> |
        <span style='color:#fd7e14;'><strong>Extended Overdue:</strong> {$extendedOverdue}</span>
    ";


          } elseif ($stat['label'] == "Cupboards") {
            $query = $dbh->prepare("SELECT COUNT(DISTINCT rack_no) AS racks_count FROM tbl_racks");
            $query->execute();
            $result = $query->fetch(PDO::FETCH_ASSOC);
            $tooltip = "Total cupboards: {$result['racks_count']}";
          }

          $query = $dbh->prepare($stat["query"]);

          $query->execute();
          $count = $query->rowCount();

          echo "
    <div class='col-md-4 mb-4'>
        <a href='{$stat['link']}' style='text-decoration: none; color: inherit;'>
            <div class='info-card border-left-{$stat['class']} text-center p-4'>
                <i class='fa {$stat['icon']} fa-4x text-{$stat['class']} mb-2'></i>
                <h3>{$count}</h3>
                <h6>{$stat['label']}</h6>
                <div class='info-tooltip'>{$tooltip}</div>
            </div>
        </a>
    </div>";
        }

        ?>

      </div>
      <!-- </div> -->

      <!-- Smaller Carousel Section -->
      <div class="container mt-4">
        <div id="carousel-example" class="carousel slide" data-ride="carousel"
          style="max-width: 700px; margin: auto; border-radius: 15px; overflow: hidden; box-shadow: 0 4px 16px rgba(0,0,0,0.1);">
          <div class="carousel-inner">
            <div class="carousel-item active">
              <img class="d-block w-100" src="../assets/img/l_img1.jpg" alt="Slide 1"
                style="height: 300px; object-fit: cover;">
            </div>
            <div class="carousel-item">
              <img class="d-block w-100" src="../assets/img/l_img2.jpg" alt="Slide 2"
                style="height: 300px; object-fit: cover;">
            </div>
            <div class="carousel-item">
              <img class="d-block w-100" src="../assets/img/l_img3.jpg" alt="Slide 3"
                style="height: 300px; object-fit: cover;">
            </div>
          </div>
          <a class="carousel-control-prev" href="#carousel-example" role="button" data-slide="prev">
            <span class="carousel-control-prev-icon" aria-hidden="true"></span>
            <span class="sr-only">Previous</span>
          </a>
          <a class="carousel-control-next" href="#carousel-example" role="button" data-slide="next">
            <span class="carousel-control-next-icon" aria-hidden="true"></span>
            <span class="sr-only">Next</span>
          </a>
        </div>
      </div>


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

    <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>
  <?php } ?>