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

    
$data json_decode(file_get_contents("php://input"), true);
    
$id $data['id'] ?? '';

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

    
// check if the film is used in any shift
    
$sql "SELECT COUNT(*) FROM citeLeParis_shift WHERE fk_film = ?";
    
$stmt mysqli_prepare($dbc$sql);

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

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

    if (
$shiftCount 0) {
        
// film is used in at least one shift, cannot delete
        
http_response_code(403);
        echo 
json_encode(['status' => 'error''message' => 'This film is used in one or more shifts and cannot be deleted.']);
        
mysqli_close($dbc);
        exit;
    }

    
// delete from film-language relation table first
    
$sql "DELETE FROM citeLeParis_hasLanguage WHERE pkfk_film = ?";
    
$stmt mysqli_prepare($dbc$sql);

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

    
mysqli_stmt_bind_param($stmt'i'$id);
    
mysqli_stmt_execute($stmt);
    
mysqli_stmt_close($stmt);

    
// now delete the film
    
$sql "DELETE FROM citeLeParis_film WHERE pk_filmID = ?";
    
$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 film.']);
        exit;
    }

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