<?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;
}

// Only allow POST
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'error' => 'Invalid request method']);
    exit;
}

try {

    // ── Get ID ─────────────────────────────────────
    $shift_id = isset($_POST['id']) ? (int)$_POST['id'] : 0;

    if ($shift_id <= 0) {
        echo json_encode(['success' => false, 'error' => 'Invalid shift ID']);
        exit;
    }

    // ── Check if exists ────────────────────────────
    $check = $conn->query("SELECT id FROM shifts WHERE id = $shift_id");
    if (!$check || $check->num_rows === 0) {
        echo json_encode(['success' => false, 'error' => 'Shift record not found']);
        exit;
    }

    // ── Delete ─────────────────────────────────────
    $sql = "DELETE FROM shifts WHERE id = $shift_id";

    if (!$conn->query($sql)) {
        throw new Exception('Delete failed: ' . $conn->error);
    }

    if ($conn->affected_rows === 0) {
        echo json_encode(['success' => false, 'error' => 'Nothing deleted']);
        exit;
    }

    ob_clean();
    echo json_encode([
        'success' => true,
        'message' => 'Shift deleted successfully',
        'deleted_id' => $shift_id
    ]);

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

ob_end_flush();
?>