<?php
// Handle KDM upload and processing
if (isset($_POST['action']) && $_POST['action'] === 'upload_kdm') {
    
$film_id intval($_POST['film_id']);
    
    
// Check if a file was uploaded
    
if (isset($_FILES['kdm_file']) && $_FILES['kdm_file']['error'] === UPLOAD_ERR_OK) {
        
$kdm_file $_FILES['kdm_file']['tmp_name'];
        
$kdm_name $_FILES['kdm_file']['name'];
        
        
// Use a unique subdirectory in the existing kdm directory
        
$extract_dir $kdm_temp_dir uniqid('kdm_');
        
        
// Only try to create the directory if it doesn't exist
        
if (!file_exists($extract_dir)) {
            
// If we can't create it, use the main kdm directory
            
if (!@mkdir($extract_dir0755true)) {
                
$extract_dir $kdm_temp_dir;
            }
        }
        
        
// Process the KDM file
        
$kdm_dates processKdmFile($kdm_file$extract_dir);
        
        if (
$kdm_dates) {
            
// Update the film record
            
$update_stmt $dbc->prepare("UPDATE CINE_Film SET kdmStart = ?, kdmEnd = ? WHERE pk_Film = ?");
            
$update_stmt->bind_param('ssi'$kdm_dates['start'], $kdm_dates['end'], $film_id);
            
            if (
$update_stmt->execute()) {
                
$msg "KDM dates updated successfully! Valid from " date('Y-m-d H:i'strtotime($kdm_dates['start'])) . " to " date('Y-m-d H:i'strtotime($kdm_dates['end']));
                
$msgType 'success';
            } else {
                
$msg "Error updating KDM dates: " $update_stmt->error;
                
$msgType 'error';
            }
            
$update_stmt->close();
        } else {
            
$msg "Could not find KDM dates in the uploaded file.";
            
$msgType 'error';
        }
        
        
// Clean up temporary files
        
cleanupKdmDirectory($extract_dir$kdm_temp_dir);
    } else {
        
$msg "No file uploaded or upload error occurred.";
        
$msgType 'error';
    }
}

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    
// Create new film
    
if (isset($_POST['action']) && $_POST['action'] === 'create') {
        
$name trim($_POST['name']);
        
$length = isset($_POST['length']) ? intval($_POST['length']) : 0;
        
$releaseDate $_POST['releaseDate'];
        
$kdmStart = !empty($_POST['kdmStart']) ? $_POST['kdmStart'] : null;
        
$kdmEnd = !empty($_POST['kdmEnd']) ? $_POST['kdmEnd'] : null;
        
        
// Default image path
        
$imagePath $default_image;

        
// Handle image upload for new films only
        
if (isset($_FILES['image']) && $_FILES['image']['size'] > 0) {
            
$file_extension pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION);
            
$new_filename 'movie_' time() . '_' mt_rand(10009999) . '.' $file_extension;
            
$upload_path $relative_image_dir $new_filename;
            
            
// Move the uploaded file
            
if (move_uploaded_file($_FILES['image']['tmp_name'], $upload_path)) {
                
$imagePath $upload_path;
            } else {
                
$msg "Failed to upload image: " error_get_last()['message'];
                
$msgType 'error';
            }
        }
        
        
// Validate input
        
if (empty($name)) {
            
$msg 'Film name cannot be empty.';
            
$msgType 'error';
        } elseif (
$length <= 0) {
            
$msg 'Film length must be greater than 0.';
            
$msgType 'error';
        } elseif (empty(
$releaseDate)) {
            
$msg 'Release date cannot be empty.';
            
$msgType 'error';
        } else {
            
// Prepare the query
            
$query "INSERT INTO CINE_Film (name, length, releaseDate, imagePath, kdmStart, kdmEnd) 
                     VALUES (?, ?, ?, ?, ?, ?)"
;
            
$stmt $dbc->prepare($query);
            
$stmt->bind_param('sissss'$name$length$releaseDate$imagePath$kdmStart$kdmEnd);
            
            if (
$stmt->execute()) {
                
$msg 'Film added successfully!';
                
$msgType 'success';
            } else {
                
$msg 'Error adding film: ' $stmt->error;
                
$msgType 'error';
            }
            
$stmt->close();
        }
    }
    
    
// Update existing film
    
if (isset($_POST['action']) && $_POST['action'] === 'update') {
        try {
            
$id intval($_POST['id']);
            
$name trim($_POST['name']);
            
$length = isset($_POST['length']) ? intval($_POST['length']) : 0;
            
$releaseDate $_POST['releaseDate'];
            
$kdmStart = !empty($_POST['kdmStart']) ? $_POST['kdmStart'] : null;
            
$kdmEnd = !empty($_POST['kdmEnd']) ? $_POST['kdmEnd'] : null;
            
            
// Simple update query without redirect
            
$query "UPDATE CINE_Film SET name = ?, length = ?, releaseDate = ?, kdmStart = ?, kdmEnd = ? WHERE pk_Film = ?";
            
$stmt $dbc->prepare($query);
            
$stmt->bind_param('sisssi'$name$length$releaseDate$kdmStart$kdmEnd$id);
            
            if (
$stmt->execute()) {
                
$msg 'Film updated successfully!';
                
$msgType 'success';
            } else {
                
$msg 'Error updating film: ' $stmt->error;
                
$msgType 'error';
            }
            
$stmt->close();
        } catch (
Exception $e) {
            
$msg 'Error: ' $e->getMessage();
            
$msgType 'error';
        }
    }
    
    
// Delete film
    
if (isset($_POST['action']) && $_POST['action'] === 'delete') {
        
$id intval($_POST['id']);
        
        
// Check if this film is used in any plages
        
$checkStmt $dbc->prepare("SELECT COUNT(*) as count FROM CINE_Plage WHERE fk_Film = ?");
        
$checkStmt->bind_param('i'$id);
        
$checkStmt->execute();
        
$checkResult $checkStmt->get_result();
        
$usageCount $checkResult->fetch_assoc()['count'];
        
$checkStmt->close();
        
        if (
$usageCount 0) {
            
$msg 'Cannot delete: This film is used in ' $usageCount ' schedule entries.';
            
$msgType 'error';
        } else {
            
// Delete the film
            
$deleteStmt $dbc->prepare("DELETE FROM CINE_Film WHERE pk_Film = ?");
            
$deleteStmt->bind_param('i'$id);
            
            if (
$deleteStmt->execute()) {
                
$msg 'Film deleted successfully!';
                
$msgType 'success';
            } else {
                
$msg 'Error deleting film: ' $deleteStmt->error;
                
$msgType 'error';
            }
            
$deleteStmt->close();
        }
    }
}