<?php
error_reporting(0);
ini_set('display_errors', 0);
ob_start();
require_once '../../config/config.php';

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

// DataTables server-side params
$draw = (int)($_GET['draw'] ?? 1);
$start = (int)($_GET['start'] ?? 0);
$length = (int)($_GET['length'] ?? 10);
$searchValue = trim($_GET['search']['value'] ?? '');

$whereParts = [];
$params = [];
if ($searchValue !== '') {
    $whereParts[] = "(title LIKE ? OR remarks LIKE ? OR holiday_date LIKE ? OR type LIKE ?)";
    $like = "%$searchValue%";
    array_push($params, $like, $like, $like, $like);
}

// Custom filters
$from = trim($_GET['from_date'] ?? '');
$to = trim($_GET['to_date'] ?? '');
$type = trim($_GET['type'] ?? '');

if ($from !== '') { $whereParts[] = "holiday_date >= ?"; $params[] = $from; }
if ($to !== '') { $whereParts[] = "holiday_date <= ?"; $params[] = $to; }
if ($type !== '') { $whereParts[] = "type = ?"; $params[] = $type; }

$where = '';
if (!empty($whereParts)) { $where = 'WHERE ' . implode(' AND ', $whereParts); }

$totalQuery = $pdo->query("SELECT COUNT(*) FROM holidays");
$recordsTotal = (int)$totalQuery->fetchColumn();

$countStmt = $pdo->prepare("SELECT COUNT(*) FROM holidays $where");
$countStmt->execute($params);
$recordsFiltered = (int)$countStmt->fetchColumn();

$stmt = $pdo->prepare("SELECT id, holiday_date, title, type, COALESCE(remarks,'') AS remarks FROM holidays $where ORDER BY holiday_date DESC LIMIT ?, ?");
foreach ($params as $i => $p) { $stmt->bindValue($i+1, $p, PDO::PARAM_STR); }
$stmt->bindValue(count($params)+1, $start, PDO::PARAM_INT);
$stmt->bindValue(count($params)+2, $length, PDO::PARAM_INT);
$stmt->execute();
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);

echo json_encode([
    'draw' => $draw,
    'recordsTotal' => $recordsTotal,
    'recordsFiltered' => $recordsFiltered,
    'data' => $data
]);
?>


