<?php
include './connection.php';

// Retrieve court ID and date from the GET request
$courtId = isset($_GET['courtid']) ? $_GET['courtid'] : '';
$cdate = isset($_GET['cdate']) ? $_GET['cdate'] : '';

// Use today's date if no date is provided
if (empty($cdate)) {
    $cdate = date('Y-m-d'); // Get the current date in YYYY-MM-DD format
}

// Base query to fetch the cause list
$query = "SELECT c.ID, dc.court_name, c.causelist_date, c.file_link 
          FROM causelist c 
          JOIN district_courts dc ON c.court_id = dc.ID 
          WHERE c.causelist_date = ?";

// Append court ID conditionally
if (!empty($courtId)) {
    $query .= " AND c.court_id = ?";
}

$stmt = $conn->prepare($query); // Prepare the query

// Bind parameters based on the presence of court ID
if (!empty($courtId)) {
    $stmt->bind_param('si', $cdate, $courtId); // Bind date and court ID
} else {
    $stmt->bind_param('s', $cdate); // Bind only the date
}

$stmt->execute(); // Execute the query
$result = $stmt->get_result(); // Get the result set

// Check if there are records
if ($result->num_rows > 0) {
    echo "<table class='table table-bordered'>
            <thead>
                <tr>
                    <th>#</th>
                    <th>Court Name</th>
                    <th>Date</th>
                    <th>File Link</th>
                </tr>
            </thead>
            <tbody>";
    $counter = 1;
    while ($row = $result->fetch_assoc()) {
        $filePath = ltrim($row['file_link'], './'); // Remove './' or '.' at the beginning of the path
        $fullPath = "./Administrator/" . $filePath; // Prepend './Administrator/'

        echo "<tr>
                <td>{$counter}</td>
                <td>{$row['court_name']}</td>
                <td>{$row['causelist_date']}</td>
                <td><a href='{$fullPath}' target='_blank'>View File</a></td>
              </tr>";
        $counter++;
    }
    echo "</tbody></table>";
} else {
    echo "<div class='alert alert-warning'>No records found for the selected date.</div>";
}
?>
