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

// Credenciales de conexión
$servername = "localhost";
$username = "farmacia_onlydi2025";
$password = "1corintios13";
$database = "farmacia_sufarma2025";

// Conexión a la base de datos
$conn = new mysqli($servername, $username, $password, $database);
if ($conn->connect_error) {
    die(json_encode(['error' => 'Error de conexión: ' . $conn->connect_error]));
}

// Obtener parámetros de filtro
$filter_type = isset($_GET['filter_type']) ? $_GET['filter_type'] : 'day';
$date = isset($_GET['date']) ? $_GET['date'] : date('Y-m-d');
$sucursal_id = isset($_GET['sucursal_id']) ? $_GET['sucursal_id'] : '';

// Calcular el rango de fecha según el filtro seleccionado
$start_date = '';
$end_date = '';

switch ($filter_type) {
    case 'day':
        $start_date = $date . " 00:00:00";
        $end_date = $date . " 23:59:59";
        break;
    case 'week':
        // Se asume que la semana inicia el lunes
        $dt = new DateTime($date);
        $dt->setISODate($dt->format("o"), $dt->format("W"));
        $start_date = $dt->format("Y-m-d") . " 00:00:00";
        $dt->modify('+6 days');
        $end_date = $dt->format("Y-m-d") . " 23:59:59";
        break;
    case 'month':
        $start_date = date("Y-m-01", strtotime($date)) . " 00:00:00";
        $end_date = date("Y-m-t", strtotime($date)) . " 23:59:59";
        break;
    case 'year':
        $start_date = date("Y-01-01", strtotime($date)) . " 00:00:00";
        $end_date = date("Y-12-31", strtotime($date)) . " 23:59:59";
        break;
    default:
        $start_date = $date . " 00:00:00";
        $end_date = $date . " 23:59:59";
}

// Consulta SQL con JOIN para obtener el nombre de la sucursal
$sql = "SELECT ve.id, ve.fecha_y_hora, ve.descripcion, ve.precio, s.nombre as sucursal 
        FROM ventas_especiales ve
        LEFT JOIN sucursales s ON ve.sucursal_id = s.id
        WHERE ve.fecha_y_hora BETWEEN ? AND ?";

if (!empty($sucursal_id)) {
    $sql .= " AND ve.sucursal_id = ?";
}

$stmt = $conn->prepare($sql);
if (!$stmt) {
    die(json_encode(['error' => 'Error en la preparación: ' . $conn->error]));
}

if (!empty($sucursal_id)) {
    $stmt->bind_param("sss", $start_date, $end_date, $sucursal_id);
} else {
    $stmt->bind_param("ss", $start_date, $end_date);
}

$stmt->execute();
$result = $stmt->get_result();

$sales = [];
while ($row = $result->fetch_assoc()) {
    $sales[] = $row;
}

echo json_encode($sales);
$stmt->close();
$conn->close();
?>
