<?php
    session_start
();
    
header('Content-Type: application/json');

    require_once 
'../DB/db_credentials.php';
    require_once 
'../DB/db_connection.php';

    function 
isPlanPassed($plan) {
        
$endTimestamp strtotime("+{$plan['weeks']} weeks -1 day"strtotime($plan['fromDate']));
        return (
time() > $endTimestamp);
    }

    function 
isPlanActive($plan) {
        
$startTimestamp strtotime($plan['fromDate']);
        
$activeStart $startTimestamp 7*24*3600;
        
$endTimestamp strtotime("+{$plan['weeks']} weeks -1 day"$startTimestamp);
        
$now time();
        return (
$now >= $activeStart && $now <= $endTimestamp);
    }

    
$planId $_POST['plan_id'] ?? null;
    
    if (!
$planId) {
        die(
"No plan specified");
    }

    
$stmt mysqli_prepare($dbc"SELECT * FROM citeLeParis_plan WHERE pk_plan = ?");
    
mysqli_stmt_bind_param($stmt'i'$planId);
    
mysqli_stmt_execute($stmt);
    
$result mysqli_stmt_get_result($stmt);
    
$plan mysqli_fetch_assoc($result);

    if (!
$plan) {
        die(
"Plan not found");
    }

    if (
isPlanPassed($plan) || isPlanActive($plan)) {
        die(
"Cannot delete active or passed plans");
    }

    
$stmt mysqli_prepare($dbc"DELETE FROM citeLeParis_plan WHERE pk_plan = ?");
    
mysqli_stmt_bind_param($stmt'i'$planId);
    
mysqli_stmt_execute($stmt);

    
header('Location: manage_plans.php');
    exit;
?>