<?php

require_once '../../core/config.php';
require_once '../../core/session.php';
require_once '../../core/database.php';
require_once '../../core/permissions.php'; // En los _store.php asegúrate de ponerlo junto a los otros require_once

require_login();
require_permission('module.crm'); // Bloqueo de acceso

$pdo = db();

$opportunityId = isset($_POST['opportunity_id']) ? (int) $_POST['opportunity_id'] : 0;
$customerId = isset($_POST['customer_id']) ? (int) $_POST['customer_id'] : null;
$customerName = isset($_POST['customer_name']) ? trim($_POST['customer_name']) : '';
$activityType = isset($_POST['activity_type']) ? $_POST['activity_type'] : 'nota';
$title = isset($_POST['title']) ? trim($_POST['title']) : '';
$description = isset($_POST['description']) ? trim($_POST['description']) : '';
$activityDate = isset($_POST['activity_date']) && $_POST['activity_date'] !== ''
    ? date('Y-m-d H:i:s', strtotime($_POST['activity_date']))
    : date('Y-m-d H:i:s');
$ownerName = isset($_POST['owner_name']) ? trim($_POST['owner_name']) : '';

if ($opportunityId <= 0 || $title === '') {
    die('Datos incompletos.');
}

$stmt = $pdo->prepare("
    INSERT INTO crm_activities
    (
        opportunity_id,
        customer_id,
        customer_name,
        activity_type,
        title,
        description,
        activity_date,
        owner_name
    )
    VALUES (?, ?, ?, ?, ?, ?, ?, ?)
");

$stmt->execute(array(
    $opportunityId,
    $customerId,
    $customerName,
    $activityType,
    $title,
    $description,
    $activityDate,
    $ownerName
));

// ==========================================
// 🔥 NUEVO: Manejo de respuesta AJAX
// ==========================================
if (isset($_POST['ajax']) && $_POST['ajax'] == '1') {
    header('Content-Type: application/json');
    echo json_encode(['success' => true]);
    exit;
}

// Comportamiento normal (Fallback)
header('Location: /modules/crm/opportunity.php?id=' . $opportunityId);
exit;