<?php
require_once '../../core/config.php';
require_once '../../core/session.php';
require_once '../../core/permissions.php';
require_once '../../core/database.php';
require_once '../../services/crm/CrmCalendarService.php';

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

if (!is_logged_in() || !user_can('module.crm')) {
    echo json_encode(['success' => false, 'error' => 'Acceso denegado o sesión expirada.']);
    exit;
}

$title = isset($_POST['title']) ? trim($_POST['title']) : '';
$ownerUserId = isset($_POST['owner_user_id']) ? (int)$_POST['owner_user_id'] : 0;
$eventType = isset($_POST['event_type']) ? trim($_POST['event_type']) : 'accion';
$startDate = isset($_POST['start_date']) ? trim($_POST['start_date']) : '';
$startTime = isset($_POST['start_time']) ? trim($_POST['start_time']) : '10:00';
$endDate = isset($_POST['end_date']) ? trim($_POST['end_date']) : '';
$endTime = isset($_POST['end_time']) ? trim($_POST['end_time']) : '10:15';
$isAllDay = isset($_POST['is_all_day']) && $_POST['is_all_day'] === '1';

if (empty($title) || !$ownerUserId || empty($startDate)) {
    echo json_encode(['success' => false, 'error' => 'Por favor complete el título, la fecha y el ejecutivo responsable.']);
    exit;
}

// Formatear tiempos para la Base de Datos (MySQL DATETIME)
if ($isAllDay) {
    $startFull = $startDate . ' 00:00:00';
    $endFull = (!empty($endDate) ? $endDate : $startDate) . ' 23:59:59';
} else {
    $startFull = $startDate . ' ' . $startTime . ':00';
    $endFull = (!empty($endDate) ? $endDate : $startDate) . ' ' . $endTime . ':00';
}

try {
    $calendarService = new CrmCalendarService($ownerUserId);
    $eventId = $calendarService->addManualEvent($title, $startFull, $endFull, $isAllDay, $eventType, null);
    echo json_encode(['success' => true, 'event_id' => $eventId]);
} catch (Exception $e) {
    echo json_encode(['success' => false, 'error' => 'Error en la sincronización: ' . $e->getMessage()]);
}
exit;