<?php
session_start();
if (!isset($_SESSION['role']) || $_SESSION['role'] !== 'admin') {
    header("Location: login.html");
    exit();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Admin Dashboard | NCShoesT</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
  <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.5/font/bootstrap-icons.css" rel="stylesheet">
  <style>
    body {
      font-family: 'Segoe UI', sans-serif;
      background: linear-gradient(120deg, #0b3d0b, #14532d, #064e3b, #022c22, #0b3d0b);
      background-size: 1000% 1000%;
      animation: vividGreenGradient 20s ease infinite;
      color: white;
      margin: 0;
      padding: 0;
    }

    @keyframes vividGreenGradient {
      0% { background-position: 0% 50%; }
      50% { background-position: 100% 50%; }
      100% { background-position: 0% 50%; }
    }

    .sidebar {
      width: 250px;
      height: 100vh;
      background-color: rgba(5, 20, 5, 0.95);
      position: fixed;
      padding: 30px 20px;
      z-index: 1000;
    }

    .sidebar h3 {
      color: white;
      margin-bottom: 30px;
      font-weight: bold;
    }

    .sidebar a {
      display: block;
      color: #e5e5e5;
      margin-bottom: 15px;
      text-decoration: none;
      padding: 12px 15px;
      border-radius: 8px;
      font-weight: 500;
      transition: background-color 0.2s ease;
    }

    .sidebar a.active,
    .sidebar a:hover {
      background-color: #198754;
      color: white;
    }

    .content {
      margin-left: 270px;
      padding: 40px 30px;
    }

    .card {
      background-color: white;
      color: #14532d;
      border-radius: 12px;
      padding: 20px;
      box-shadow: 0 5px 20px rgba(0,0,0,0.2);
    }

    .btn-logout {
      background-color: #c0392b;
      color: white;
      font-weight: 500;
      padding: 10px;
      border-radius: 8px;
      margin-top: 30px;
    }

    .btn-logout:hover {
      background-color: #a93226;
    }

    @media (max-width: 768px) {
      .sidebar {
        width: 100%;
        height: auto;
        position: relative;
      }

      .content {
        margin-left: 0;
        padding: 20px;
      }
      #exportPDF {
  opacity: 0;
  transform: translateY(-20px);
  transition: opacity 0.6s ease, transform 0.6s ease;
  pointer-events: none;
}

#exportPDF.show {
  opacity: 1;
  transform: translateY(0);
  pointer-events: auto;
}

    }


    .export-pdf-btn {
  background: linear-gradient(90deg, #198754 60%, #14532d 100%);
  border: none;
  color: #fff;
  font-size: 1.08rem;
  border-radius: 8px;c
  transition: background 1s, box-shadow 1s, transform 1s;
  box-shadow: 0 2px 8px rgba(20, 83, 45, 0.15);
}


.export-pdf-btn:hover, .export-pdf-btn:focus {
  background: linear-gradient(90deg, #14532d 60%, #198754 100%);
  color: #fff;
  box-shadow: 0 4px 16px rgba(20, 83, 45, 0.25);
  transform: translateY(-2px) scale(1.03);
  outline: none;
}

  </style>
  <?php require 'db.php'; ?>
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
</head>
<body>

<?php include 'admin_sidebar.php'; ?>

<div class="content">
  <h3><i class="bi bi-bar-chart-line me-2"></i>Sales Report</h3>

  <form class="row g-3 mt-3 mb-4" method="GET">
    <?php
    // Get filter dates from GET parameters and sanitize
    $start_date = isset($_GET['start_date']) ? $_GET['start_date'] : '';
    $end_date = isset($_GET['end_date']) ? $_GET['end_date'] : '';
    ?>
    <div class="col-md-4">
      <label for="startDate" class="form-label">Start Date</label>
      <input type="date" class="form-control" id="startDate" name="start_date" value="<?php echo htmlspecialchars($start_date); ?>">
    </div>
    <div class="col-md-4">
      <label for="endDate" class="form-label">End Date</label>
      <input type="date" class="form-control" id="endDate" name="end_date" value="<?php echo htmlspecialchars($end_date); ?>">
    </div>
    <div class="col-md-4 d-flex align-items-end">
      <button type="submit" class="btn btn-success w-100"><i class="bi bi-funnel me-1"></i>Filter Report</button>
    </div>
  </form>

  <?php if (!empty($_GET['start_date']) || !empty($_GET['end_date'])): ?>
  <div class="d-flex justify-content-center mb-4">
  <button id="exportPDF" type="button"
    class="btn btn-success export-pdf-btn px-4 py-2 d-flex align-items-center gap-2 shadow"
    title="Export the sales table to PDF">
    <i class="bi bi-file-earmark-pdf fs-5"></i>
    <span class="fw-semibold">Export Sales Table to PDF</span>
  </button>
</div>
<?php endif; ?>

  <div class="card">
    <div id="reportTableArea" class="table-responsive">
      <table class="table table-bordered table-hover text-center align-middle mb-0">
        <thead class="table-success text-dark">
          <tr>
            <th>Date</th>
            <th>Order ID</th>
            <th>Customer</th>
            <th>Items</th>
            <th>Total Amount</th>
          </tr>
        </thead>
        <tbody>
<?php
// Initialize query and parameters
$sql = "SELECT o.order_id, o.customer_name, o.final_total, o.created_at,
        (SELECT COUNT(*) FROM order_items WHERE order_items.order_id = o.order_id) AS item_count
        FROM orders o";

$conditions = [];
$params = [];
$types = "";

// Validate and add date filters if provided
if (!empty($start_date)) {
    $conditions[] = "DATE(o.created_at) >= ?";
    $params[] = $start_date;
    $types .= "s";
}
if (!empty($end_date)) {
    $conditions[] = "DATE(o.created_at) <= ?";
    $params[] = $end_date;
    $types .= "s";
}

// Append WHERE clause if there are conditions
if (count($conditions) > 0) {
    $sql .= " WHERE " . implode(" AND ", $conditions);
}

$sql .= " ORDER BY o.created_at DESC";

// Prepare and execute statement
$stmt = $conn->prepare($sql);

if ($stmt) {
    if (count($params) > 0) {
        $stmt->bind_param($types, ...$params);
    }
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows > 0) {
        while ($row = $result->fetch_assoc()) {
            echo "<tr>";
            echo "<td>" . date('Y-m-d', strtotime($row['created_at'])) . "</td>";
            echo "<td>#{$row['order_id']}</td>";
            echo "<td>" . htmlspecialchars($row['customer_name']) . "</td>";
            echo "<td>{$row['item_count']}</td>";
            echo "<td>₱" . number_format($row['final_total'], 2) . "</td>";
            echo "</tr>";
        }
    } else {
        echo "<tr><td colspan='5'>No orders found for the selected date range.</td></tr>";
    }

    $stmt->close();
} else {
    echo "<tr><td colspan='5'>Error preparing the query.</td></tr>";
}
?>
        </tbody>
      </table>
    </div>
  </div>

  <div class="card mt-4">
    <h5 class="mb-3"><i class="bi bi-graph-up-arrow me-1"></i>Sales Chart</h5>
    <div style="height: 300px; background-color: #f8f9fa; border-radius: 10px; display: flex; align-items: center; justify-content: center;">
      <span class="text-muted">[Chart Placeholder]</span>
    </div>
  </div>
</div>

<script>

document.addEventListener("DOMContentLoaded", function() {
  const exportBtn = document.getElementById("exportPDF");

  if (exportBtn) {
    // Delay to apply the animation
    setTimeout(() => {
      exportBtn.classList.add("show");
    }, 300); // Adjust delay as needed

    exportBtn.addEventListener("click", function(e) {
      e.preventDefault();

      const { jsPDF } = window.jspdf;
      const pdf = new jsPDF('p', 'mm', 'a4');
      const tableArea = document.getElementById("reportTableArea");

      exportBtn.style.display = "none";

      html2canvas(tableArea, { scale: 2 }).then(canvas => {
        exportBtn.style.display = "";

        const imgData = canvas.toDataURL("image/png");
        const pdfWidth = pdf.internal.pageSize.getWidth();
        const imgProps = pdf.getImageProperties(imgData);
        const imgHeight = (imgProps.height * pdfWidth) / imgProps.width;
        let heightLeft = imgHeight;
        let position = 0;
        const pdfHeight = pdf.internal.pageSize.getHeight();

        pdf.addImage(imgData, 'PNG', 0, position, pdfWidth, imgHeight);
        heightLeft -= pdfHeight;

        while (heightLeft > 0) {
          position = heightLeft - imgHeight;
          pdf.addPage();
          pdf.addImage(imgData, 'PNG', 0, position, pdfWidth, imgHeight);
          heightLeft -= pdfHeight;
        }

        pdf.save("sales-report.pdf");
      });
    });
  }
});


</script>

</body>
</html>


can you make the chart functional