<?php
ob_start();
include("../../../include/startup.php");
ob_clean();

header('Content-Type: application/json');
error_reporting(0);

if (!isset($conn) || !$conn) {
    echo json_encode(['success' => false, 'error' => 'DB connection failed']);
    exit;
}

try {
    $current_page = isset($_GET['current_page']) ? max(1, (int)$_GET['current_page']) : 1;
    $per_page     = isset($_GET['per_page'])     ? max(1, (int)$_GET['per_page'])     : 50;
    $offset       = ($current_page - 1) * $per_page;
    $period       = isset($_GET['period'])       ? $_GET['period'] : 'today';
    $employee_id  = isset($_GET['employee_id'])  ? (int)$_GET['employee_id'] : 0;

    // Date range based on period
    switch ($period) {
        case 'weekly':
            $date_from = date('Y-m-d', strtotime('monday this week'));
            $date_to   = date('Y-m-d', strtotime('sunday this week'));
            break;
        case 'monthly':
            $date_from = date('Y-m-01');
            $date_to   = date('Y-m-t');
            break;
        case 'today':
        default:
            $date_from = date('Y-m-d');
            $date_to   = date('Y-m-d');
            break;
    }

    $where = ["DATE(s.start_time) BETWEEN '$date_from' AND '$date_to'"];
    if ($employee_id > 0) {
        $where[] = "s.user_id = $employee_id";
    }
    $where_clause = implode(' AND ', $where);

    // Count
    $count_result  = $conn->query("SELECT COUNT(*) as total FROM shifts s WHERE $where_clause");
    $total_records = $count_result->fetch_assoc()['total'];
    $total_pages   = ceil($total_records / $per_page);

    // Fetch
    $query = "
        SELECT 
            s.id,
            s.user_id,
            s.start_time,
            s.end_time,
            s.total_hours,
            s.status,
            a.uname,
            a.clock_no
        FROM shifts s
        LEFT JOIN admin a ON s.user_id = a.id
        WHERE $where_clause
        ORDER BY s.start_time DESC
        LIMIT $per_page OFFSET $offset
    ";

    $result = $conn->query($query);
    if (!$result) throw new Exception($conn->error);

    $rows = [];
    while ($row = $result->fetch_assoc()) $rows[] = $row;

    ob_clean();
    echo json_encode([
        'success' => true,
        'data'    => $rows,
        'pagination' => [
            'current_page'  => $current_page,
            'per_page'      => $per_page,
            'total_records' => (int)$total_records,
            'total_pages'   => (int)$total_pages,
            'showing_from'  => $offset + 1,
            'showing_to'    => min($offset + $per_page, $total_records)
        ]
    ]);

} catch (Exception $e) {
    ob_clean();
    echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}
ob_end_flush();
?>