<?php
session_start();
header('Content-Type: application/json');
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../includes/auth.php';

if (!isLoggedIn()) { echo json_encode(['status'=>'error','message'=>'Silakan login.']); exit; }

$absensiId = (int)($_POST['absensi_id'] ?? 0);
$userId = $_SESSION['user_id'];

// Verify ownership
$stmt = $pdo->prepare("SELECT a.*, k.jam_mulai, k.hari FROM absensi a JOIN kelas k ON a.kelas_id = k.id WHERE a.id = ? AND a.user_id = ?");
$stmt->execute([$absensiId, $userId]);
$absensi = $stmt->fetch();

if (!$absensi) { echo json_encode(['status'=>'error','message'=>'Data tidak ditemukan.']); exit; }

// Check 2-hour rule (comparing against class start time)
$dayMap = ['Senin'=>'Monday','Selasa'=>'Tuesday','Rabu'=>'Wednesday','Kamis'=>'Thursday','Jumat'=>'Friday','Sabtu'=>'Saturday','Minggu'=>'Sunday'];
$kelasDayName = $dayMap[$absensi['hari']] ?? '';
$todayDayName = date('l');

if (strtolower($todayDayName) === strtolower($kelasDayName)) {
    $classTimestamp = strtotime(date('Y-m-d') . ' ' . $absensi['jam_mulai']);
    // If class time has already passed today, it points to next week's class
    if ($classTimestamp < time()) {
        $classTimestamp = strtotime("next " . $kelasDayName . " " . $absensi['jam_mulai']);
    }
} else {
    $classTimestamp = strtotime("next " . $kelasDayName . " " . $absensi['jam_mulai']);
}

$diff = $classTimestamp - time();

if ($diff < 7200) { // 2 hours = 7200 seconds
    echo json_encode(['status'=>'error','message'=>'Tidak bisa cancel kurang dari 2 jam sebelum kelas dimulai.']);
    exit;
}

$pdo->beginTransaction();
try {
    $pdo->prepare("DELETE FROM absensi WHERE id = ?")->execute([$absensiId]);
    $pdo->prepare("UPDATE kelas SET sisa_slot = sisa_slot + 1 WHERE id = ?")->execute([$absensi['kelas_id']]);
    $pdo->commit();
    echo json_encode(['status'=>'success','message'=>'Booking berhasil dibatalkan.']);
} catch (Exception $e) {
    $pdo->rollBack();
    echo json_encode(['status'=>'error','message'=>'Gagal membatalkan.']);
}
