<?php
// cms/schedule-update.php
header('Content-Type: application/json');

require_once('db_connection.php');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'message' => 'Método No Permitido']);
    exit;
}

try {
    // Iniciar transacción
    $pdo->beginTransaction();

    // Sanitizar y validar inputs generales
    $schedule_badge = htmlspecialchars(strip_tags($_POST['hours-badge'] ?? ''));
    $schedule_title_1 = htmlspecialchars(strip_tags($_POST['hours-title-1'] ?? ''));
    $schedule_title_2 = htmlspecialchars(strip_tags($_POST['hours-title-2'] ?? ''));

    // Decodificar los JSON de horarios y beneficios
    $hours = json_decode($_POST['hours_json'] ?? '[]', true);
    $benefits = json_decode($_POST['benefits_json'] ?? '[]', true);

    // Insertar/Actualizar en la tabla principal
    $stmt = $pdo->query("SELECT id FROM cms_schedule ORDER BY updated_at DESC LIMIT 1");
    $currentRecord = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($currentRecord) {
        $scheduleId = $currentRecord['id'];
        $sql = "UPDATE cms_schedule SET schedule_badge=?, schedule_title_1=?, schedule_title_2=? WHERE id=?";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$schedule_badge, $schedule_title_1, $schedule_title_2, $scheduleId]);
    } else {
        $sql = "INSERT INTO cms_schedule (schedule_badge, schedule_title_1, schedule_title_2) VALUES (?, ?, ?)";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$schedule_badge, $schedule_title_1, $schedule_title_2]);
        $scheduleId = $pdo->lastInsertId();
    }
    
    // Eliminar horarios y beneficios antiguos
    if (isset($scheduleId)) {
        $stmt = $pdo->prepare("DELETE FROM cms_weekly_hours WHERE schedule_id = ?");
        $stmt->execute([$scheduleId]);
        $stmt = $pdo->prepare("DELETE FROM cms_schedule_benefits WHERE schedule_id = ?");
        $stmt->execute([$scheduleId]);

        // Insertar nuevos horarios
        $sqlHours = "INSERT INTO cms_weekly_hours (schedule_id, day, is_open, open_time, close_time) VALUES (?, ?, ?, ?, ?)";
        $stmtHours = $pdo->prepare($sqlHours);
        foreach ($hours as $hour) {
            $day = htmlspecialchars(strip_tags($hour['day'] ?? ''));
            $isOpen = intval($hour['is_open'] ?? 0);
            $openTime = $isOpen ? ($hour['open_time'] ?? NULL) : NULL;
            $closeTime = $isOpen ? ($hour['close_time'] ?? NULL) : NULL;
            if (!empty($day)) {
                $stmtHours->execute([$scheduleId, $day, $isOpen, $openTime, $closeTime]);
            }
        }

        // Insertar nuevos beneficios
        $sqlBenefit = "INSERT INTO cms_schedule_benefits (schedule_id, benefit_icon, benefit_text) VALUES (?, ?, ?)";
        $stmtBenefit = $pdo->prepare($sqlBenefit);
        foreach ($benefits as $benefit) {
            $icon = htmlspecialchars(strip_tags($benefit['icon'] ?? ''));
            $text = htmlspecialchars(strip_tags($benefit['text'] ?? ''));
            if (!empty($text)) {
                $stmtBenefit->execute([$scheduleId, $icon, $text]);
            }
        }
    }

    $pdo->commit();
    echo json_encode(['success' => true, 'message' => 'SiteFlow Actualizado Exitosamente']);
} catch (Exception $e) {
    if ($pdo->inTransaction()) {
        $pdo->rollBack();
    }
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Error: ' . $e->getMessage()]);
}
?>