<?php
error_reporting(0);
ini_set('display_errors', 0);
ob_start();

require_once '../../config/config.php';
require_once '../helper/audit_log.php';

ob_clean();
header('Content-Type: application/json');

try {
    $holiday_date = trim($_POST['holiday_date'] ?? '');
    $title = trim($_POST['title'] ?? '');
    $type = trim($_POST['type'] ?? 'Holiday');
    $remarks = trim($_POST['remarks'] ?? '');

    $errors = [];
    if ($holiday_date === '' || !preg_match('/^\d{4}-\d{2}-\d{2}$/', $holiday_date)) {
        $errors[] = 'Valid date (YYYY-MM-DD) is required.';
    }
    if ($title === '' || mb_strlen($title) < 3) {
        $errors[] = 'Title must be at least 3 characters.';
    }
    if (!in_array($type, ['Holiday','Weekend'])) {
        $errors[] = 'Invalid type.';
    }

    if ($errors) {
        echo json_encode(["status" => "error", "message" => implode(' ', $errors)]);
        exit;
    }

    $check_stmt = $pdo->prepare("SELECT id FROM holidays WHERE holiday_date = ? AND type = ?");
    $check_stmt->execute([$holiday_date, $type]);
    if ($check_stmt->fetch()) {
        echo json_encode(["status" => "error", "message" => "Entry already exists for this date and type."]);
        exit;
    }

    $stmt = $pdo->prepare("INSERT INTO holidays (holiday_date, title, type, remarks) VALUES (?, ?, ?, ?)");
    $stmt->execute([$holiday_date, $title, $type, $remarks]);
    $new_id = $pdo->lastInsertId();

    write_audit_log($pdo, [
        'module' => 'Holidays',
        'action' => 'create',
        'entity_table' => 'holidays',
        'entity_id' => $new_id,
        'after_data' => compact('holiday_date','title','type','remarks'),
        'message' => 'Holiday created successfully'
    ]);

    echo json_encode([
        'status' => 'success',
        'message' => 'Holiday saved successfully.',
        'data' => [
            'id' => (int)$new_id,
            'holiday_date' => $holiday_date,
            'title' => $title,
            'type' => $type,
            'remarks' => $remarks
        ]
    ]);
} catch (Throwable $e) {
    http_response_code(500);
    echo json_encode(['status' => 'error', 'message' => 'An error occurred while saving the holiday.']);
}
?>







