<?php
    header
('Content-Type: application/json');
    require_once 
'../DB/db_credentials.php';
    require_once 
'../DB/db_connection.php';

    
$id $_POST['id'] ?? '';

    if (!
$id) {
        
http_response_code(400);
        echo 
json_encode(['status' => 'error''message' => 'Missing shift ID.']);
        exit;
    }

    
// check if a shift has any registrations
    
$sql "SELECT COUNT(*) FROM citeLeParis_register WHERE fk_shift = ?";
    
$stmt mysqli_prepare($dbc$sql);

    if (!
$stmt) {
        
http_response_code(500);
        echo 
json_encode(['status' => 'error''message' => 'Failed to prepare statement for registration check.']);
        
mysqli_close($dbc);
        exit;
    }

    
mysqli_stmt_bind_param($stmt'i'$id);
    
mysqli_stmt_execute($stmt);
    
mysqli_stmt_bind_result($stmt$registrationCount);
    
mysqli_stmt_fetch($stmt);
    
mysqli_stmt_close($stmt);

    if (
$registrationCount 0) {
        
// shift is referenced by registrations, cannot be deleted
        
http_response_code(403);
        echo 
json_encode(['status' => 'error''message' => 'Shift has registrations and cannot be deleted.']);
        
mysqli_close($dbc);
        exit;
    }

    
// check if a shift is outdated
    
$sql "SELECT date FROM citeLeParis_shift WHERE pk_shift = ?";
    
$stmt mysqli_prepare($dbc$sql);

    if (!
$stmt) {
        
http_response_code(500);
        echo 
json_encode(['status' => 'error''message' => 'Failed to prepare statement for date check.']);
        
mysqli_close($dbc);
        exit;
    }

    
mysqli_stmt_bind_param($stmt'i'$id);
    
mysqli_stmt_execute($stmt);
    
mysqli_stmt_bind_result($stmt$shiftDate);
    
mysqli_stmt_fetch($stmt);
    
mysqli_stmt_close($stmt);

    if (!
$shiftDate) {
        
http_response_code(404);
        echo 
json_encode(['status' => 'error''message' => 'Shift not found.']);
        
mysqli_close($dbc);
        exit;
    }

    if (
strtotime($shiftDate) < strtotime(date('Y-m-d'))) {
        
http_response_code(403);
        echo 
json_encode(['status' => 'error''message' => 'Cannot delete an outdated shift.']);
        
mysqli_close($dbc);
        exit;
    }

    
// if no registrations and not outdated, proceed with delete
    
$sql "DELETE FROM citeLeParis_shift WHERE pk_shift = ?";
    
$stmt mysqli_prepare($dbc$sql);

    if (!
$stmt) {
        
http_response_code(500);
        echo 
json_encode(['status' => 'error''message' => 'Failed to prepare delete statement.']);
        
mysqli_close($dbc);
        exit;
    }

    
mysqli_stmt_bind_param($stmt'i'$id);
    
$ok mysqli_stmt_execute($stmt);
    
mysqli_stmt_close($stmt);
    
mysqli_close($dbc);

    if (!
$ok) {
        
http_response_code(500);
        echo 
json_encode(['status' => 'error''message' => 'Failed to delete shift.']);
        exit;
    }

    
http_response_code(200);
    echo 
json_encode(['status' => 'success''message' => 'Shift deleted successfully.']);
?>