<?php
$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']);
$ruta = "../";
require_once "../include/bd_pdo.php";
global $pdo;
//print_r($_POST);
if (!isset($_POST['periodo'])  || count($_POST["periodo"])==0) {
    header("Location: ../días_festivos.php?error=0");
    exit();
}
$periodoArr = $_POST['periodo'];

if (isset($_POST['rango'])) {
    $diaInicio  = new DateTime(date("Y-m-d", strtotime(str_replace("/", "-", $_POST['diaFestivo']))));
    $diaFin = new DateTime(date("Y-m-d", strtotime(str_replace("/", "-", $_POST['diaFestivoFin']))));
    $cantidad = $diaFin->diff($diaInicio);
    $date = date("Y-m-d", strtotime(str_replace("/", "-", $_POST['diaFestivo'])));
    for ($dias = 0; $dias <= $cantidad->days; $dias++) {
        
        $db->querySingle('SELECT fi_diasfestivos({'.implode(",",$fieldName).'}, :dia)', [':dia' => $date]);
            /*$sql = "SELECT fi_diasfestivos(:periodo, :dia)";
            $params = [':periodo' => $periodo, ':dia' => $date];
            query($sql, $params, false);*/
        
        $date = date("Y-m-d", strtotime($date . "+ 1 days"));
    }
    header("Location: ../días_festivos.php");
    exit();
} else {
    /*$sql = "SELECT * FROM fs_diasfestivos(null, :dia)";
    $params = [':dia' => $_POST['diaFestivo']];
    $dia_general = query($sql, $params, false);
    $sql = "SELECT * FROM fs_diasfestivos(null, null, :periodo, :dia)";
    $params = [':periodo' => $periodo, ":dia" => $_POST['diaFestivo']];
    $dia = query($sql, $params, false);*/
    //if (!$dia && !$dia_general) { //no hay repetidos
    foreach($periodoArr as $periodo){
        $db->querySingle('SELECT fi_diasfestivos({'.implode(",",$fieldName).'}, :dia)', [':dia' => $_POST['diaFestivo']]);
        /*$sql = "SELECT fi_diasfestivos(:periodo, :dia)";
        $params = [':periodo' => $periodo, ":dia" => $_POST['diaFestivo']];
        $id = query($sql, $params, false);*/
    }
        header("Location: ../días_festivos.php");
        exit();
    
    /*} else {
        header("Location: ../días_festivos.php?error=1");
        exit();
    }*/
}
