<?php
header('Content-Type: application/json');
$ruta = "../";
require_once "../class/c_login.php";

// check if the session is started
if (!isset($_SESSION['user']))
    die(json_encode(['error' => 'No se ha iniciado sesión']));

$user = unserialize($_SESSION['user']);

$horario = array_map(fn ($value) => $_POST[$value], array_filter([
    "hora" => "hora",
    "dia" => "día",
    "salon" => "salón",
    "duracion" => "duración",
], fn ($value) => !empty($_POST[$value])));

if (!empty($_POST['profesores']))
    $horario["profesores"] = "{ {$_POST['profesores']} }";

try {
    $id = $_POST['id'] ?? 0;

    $old = $db
        ->where("horario_id", $id)
        ->getOne("horario");
    
    $horario = $db
        ->where("id", $id)
        ->update("fs_horario", $horario);

    $new = $db
        ->orderBy("horario_id", "DESC")
        ->getOne("horario");
        
    $user->print_to_log("Actualización de horario", old: $old, new: $new);
} catch (Exception $e) {
    die(json_encode([
        "status" => "error",
        "message" => $e->getMessage(),
        'POST' => $_POST,
    ]));
}

die(json_encode([
    "status" => "success",
]));
