<?php
// Actualización de Bloques de fechas de disponibilidad || Update of Availability Date Blocks
// $V_idavailability --> Parameter

$strSQL = "
SELECT `idavailability`, `media_idmedia`, `startDate`, `endDate` FROM availability where `idavailability` = $V_idavailability 
";
$rsSQL = db_query($strSQL,$conn);
$data_1 = db_fetch_array($rsSQL);
$V_startDate = $data_1['startDate'];
$V_endDate = $data_1['endDate'];
$V_media = $data_1['media_idmedia'];

$strSQL = "
SELECT `idreservations`, `availability_idavailability`, `media_idmedia`, `users_user_id`, `startDate`, `endDate`, `effectiveDate`
FROM reservations
where `availability_idavailability` = $V_idavailability order by `startDate`
";
$rsSQL = db_query($strSQL,$conn);
$V_reservations = array();
while ($data_2 = db_fetch_array($rsSQL)) {
    $V_reservations[] = [$data_2['startDate'],$data_2['effectiveDate'],$data_2['endDate']];
}
$V_block = array();
if (count($V_reservations) == 0){ // No hay reservas ||No reservations
    $V_block[] = [$V_startDate,$V_endDate];
} else { // Para el caso de que haya reservas || In case there are reservations
    $limit_start = $V_startDate;
    foreach ($V_reservations as &$reservations) {
        if ( $limit_start < $reservations[0] ) {
            $V_block[] = [$limit_start,$reservations[0]];
            $limit_start = $reservations[1];
        } else {
            $limit_start = $reservations[1];
        }
    }
    if ($limit_start <> $V_endDate ) { // Resto de fechas || Rest of dates
        $V_block[] = [$limit_start,$V_endDate];
    }
    
}

$strSQL = "
DELETE FROM available_block WHERE availability_idavailability = $V_idavailability 
";
$rsSQL = db_query($strSQL,$conn); // Delete record existent of available_block

foreach ($V_block as &$block) {
    $startDate = $block[0];
    $endDate = $block[1];
		$strSQL = "
			insert INTO available_block (`availability_idavailability`, `media_idmedia`, `startDate`, `endDate`)
			values ($V_idavailability,$V_media,'$startDate','$endDate')
		";
		$rsSQL = db_query($strSQL,$conn);
}
?>