<?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 intval($data['id']);
    
$fk_shift intval($data['fk_shift']);
    
$fk_answer intval($data['fk_answer']);

    
// Get the fromDate of the related plan
    
$checkSql "
        SELECT p.fromDate
        FROM citeLeParis_register r
        JOIN citeLeParis_plan p ON r.fk_plan = p.pk_plan
        WHERE r.pk_register = ?
    "
;

    
$stmt mysqli_prepare($dbc$checkSql);
    
mysqli_stmt_bind_param($stmt"i"$id);
    
mysqli_stmt_execute($stmt);
    
mysqli_stmt_bind_result($stmt$fromDate);
    
mysqli_stmt_fetch($stmt);
    
mysqli_stmt_close($stmt);

    if (!
$fromDate) {
        echo 
json_encode(["status" => "error""message" => "Invalid registration ID."]);
        exit;
    }

    
// Check deadline
    
$deadline date('Y-m-d'strtotime($fromDate ' -1 week'));
    if (
date('Y-m-d') > $deadline) {
        echo 
json_encode(["status" => "error""message" => "Too late to modify this registration."]);
        exit;
    }

    
// Update the registration
    
$updateSql "
        UPDATE citeLeParis_register
        SET fk_shift = ?, fk_answer = ?
        WHERE pk_register = ?
    "
;

    
$stmt mysqli_prepare($dbc$updateSql);
    
mysqli_stmt_bind_param($stmt"iii"$fk_shift$fk_answer$id);
    
$success mysqli_stmt_execute($stmt);
    
mysqli_stmt_close($stmt);

    echo 
json_encode([
        
"status" => $success "success" "error",
        
"message" => $success "Registration updated!" "Update failed."
    
]);
?>