<?php 
ob_start();
header('Content-Type: application/json');
$response = ['success' => false, 'message' => 'ERROR DESCONOCIDO'];

try {
    include_once 'db_connection.php';
    require_once '../files/guardiankey.php';

    ini_set('display_errors', 0);
    ini_set('log_errors', 1);
    ini_set('error_log', __DIR__ . '/../logs/php_errors.log');
    error_reporting(E_ALL);

    $input = file_get_contents('php://input');
    $data = json_decode($input, true);

    if (json_last_error() !== JSON_ERROR_NONE) {
        error_log("Error al decodificar JSON en leads-update.php: " . json_last_error_msg());
        throw new Exception('ERROR AL PROCESAR DATOS');
    }

    if (
        !isset($data['id']) || empty(trim($data['id'])) ||
        !isset($data['first_name']) || empty(trim($data['first_name'])) ||
        !isset($data['last_name']) || empty(trim($data['last_name'])) ||
        (
            empty(trim($data['email'] ?? '')) &&
            empty(trim($data['phone'] ?? '')) &&
            empty(trim($data['mobile'] ?? ''))
        )
    ) {
        throw new Exception('DATOS OBLIGATORIOS FALTANTES');
    }

    $lead_id = filter_var($data['id'], FILTER_VALIDATE_INT);
    $first_name = filter_var(trim($data['first_name']), FILTER_SANITIZE_FULL_SPECIAL_CHARS);
    $last_name = filter_var(trim($data['last_name']), FILTER_SANITIZE_FULL_SPECIAL_CHARS);
    $company = !empty(trim($data['company'] ?? '')) ? filter_var(trim($data['company']), FILTER_SANITIZE_FULL_SPECIAL_CHARS) : null;
    $email = !empty(trim($data['email'] ?? '')) ? filter_var(trim($data['email']), FILTER_SANITIZE_EMAIL) : null;
    $phone = !empty(trim($data['phone'] ?? '')) ? preg_replace('/[^0-9()\-+ ]/', '', trim($data['phone'])) : null;
    $mobile = !empty(trim($data['mobile'] ?? '')) ? preg_replace('/[^0-9()\-+ ]/', '', trim($data['mobile'])) : null;
    $source = trim($data['source'] ?? 'Desconocida');
    $status = trim($data['status'] ?? 'Nuevo');
    $priority = trim($data['priority'] ?? 'Media');
    $street_address = !empty(trim($data['street_address'] ?? '')) ? filter_var(trim($data['street_address']), FILTER_SANITIZE_FULL_SPECIAL_CHARS) : null;
    $city = !empty(trim($data['city'] ?? '')) ? filter_var(trim($data['city']), FILTER_SANITIZE_FULL_SPECIAL_CHARS) : null;
    $state_province = !empty(trim($data['state_province'] ?? '')) ? filter_var(trim($data['state_province']), FILTER_SANITIZE_FULL_SPECIAL_CHARS) : null;
    $zip_code = !empty(trim($data['zip_code'] ?? '')) ? filter_var(trim($data['zip_code']), FILTER_SANITIZE_FULL_SPECIAL_CHARS) : null;

    if ($lead_id === false) {
        throw new Exception('ID INVALIDO');
    }

    $stmt_check_leads = $pdo->prepare("
        SELECT id FROM leads
        WHERE id != :current_lead_id AND (
                (email IS NOT NULL AND email != '' AND email = :email_check_leads)
             OR (phone IS NOT NULL AND phone != '' AND phone = :phone_check_leads)
             OR (mobile IS NOT NULL AND mobile != '' AND mobile = :mobile_check_leads)
        )
        LIMIT 1
    ");
    $stmt_check_leads->bindValue(':current_lead_id', $lead_id, PDO::PARAM_INT);
    $stmt_check_leads->bindValue(':email_check_leads', $email, $email === null ? PDO::PARAM_NULL : PDO::PARAM_STR);
    $stmt_check_leads->bindValue(':phone_check_leads', $phone, $phone === null ? PDO::PARAM_NULL : PDO::PARAM_STR);
    $stmt_check_leads->bindValue(':mobile_check_leads', $mobile, $mobile === null ? PDO::PARAM_NULL : PDO::PARAM_STR);
    $stmt_check_leads->execute();

    if ($stmt_check_leads->fetch(PDO::FETCH_ASSOC)) {
        $response['message'] = 'DUPLICADO: EMAIL O TELEFONO EN PROSPECTOS';
        if (ob_get_level() > 0) ob_end_clean();
        echo json_encode($response);
        exit;
    }

    $stmt_check_clients = $pdo->prepare("
        SELECT id FROM clients
        WHERE (email IS NOT NULL AND email != '' AND email = :email_check_clients)
           OR (phone IS NOT NULL AND phone != '' AND phone = :phone_check_clients)
           OR (mobile IS NOT NULL AND mobile != '' AND mobile = :mobile_check_clients)
        LIMIT 1
    ");
    $stmt_check_clients->bindValue(':email_check_clients', $email, $email === null ? PDO::PARAM_NULL : PDO::PARAM_STR);
    $stmt_check_clients->bindValue(':phone_check_clients', $phone, $phone === null ? PDO::PARAM_NULL : PDO::PARAM_STR);
    $stmt_check_clients->bindValue(':mobile_check_clients', $mobile, $mobile === null ? PDO::PARAM_NULL : PDO::PARAM_STR);
    $stmt_check_clients->execute();

    if ($stmt_check_clients->fetch(PDO::FETCH_ASSOC)) {
        $response['message'] = 'DUPLICADO: CONTACTO YA ES CLIENTE';
        if (ob_get_level() > 0) ob_end_clean();
        echo json_encode($response);
        exit;
    }

    $stmt = $pdo->prepare("
        UPDATE leads SET
            first_name = :first_name,
            last_name = :last_name,
            company = :company,
            email = :email,
            phone = :phone,
            mobile = :mobile,
            source = :source,
            status = :status,
            priority = :priority,
            street_address = :street_address,
            city = :city,
            state_province = :state_province,
            zip_code = :zip_code,
            updated_at = NOW()
        WHERE id = :id
    ");

    $stmt->bindParam(':first_name', $first_name, PDO::PARAM_STR);
    $stmt->bindParam(':last_name', $last_name, PDO::PARAM_STR);
    $stmt->bindParam(':company', $company, $company === null ? PDO::PARAM_NULL : PDO::PARAM_STR);
    $stmt->bindParam(':email', $email, $email === null ? PDO::PARAM_NULL : PDO::PARAM_STR);
    $stmt->bindParam(':phone', $phone, $phone === null ? PDO::PARAM_NULL : PDO::PARAM_STR);
    $stmt->bindParam(':mobile', $mobile, $mobile === null ? PDO::PARAM_NULL : PDO::PARAM_STR);
    $stmt->bindParam(':source', $source, PDO::PARAM_STR);
    $stmt->bindParam(':status', $status, PDO::PARAM_STR);
    $stmt->bindParam(':priority', $priority, PDO::PARAM_STR);
    $stmt->bindParam(':street_address', $street_address, $street_address === null ? PDO::PARAM_NULL : PDO::PARAM_STR);
    $stmt->bindParam(':city', $city, $city === null ? PDO::PARAM_NULL : PDO::PARAM_STR);
    $stmt->bindParam(':state_province', $state_province, $state_province === null ? PDO::PARAM_NULL : PDO::PARAM_STR);
    $stmt->bindParam(':zip_code', $zip_code, $zip_code === null ? PDO::PARAM_NULL : PDO::PARAM_STR);
    $stmt->bindParam(':id', $lead_id, PDO::PARAM_INT);

    if ($stmt->execute()) {
        if ($stmt->rowCount() > 0) {
            $response['success'] = true;
            $response['message'] = 'PROSPECTO ACTUALIZADO';
        } else {
             $response['success'] = true;
             $response['message'] = 'SIN CAMBIOS';
        }
    } else {
        error_log("Error al actualizar leads en leads-update.php: " . implode(" ", $stmt->errorInfo()));
        $response['message'] = 'FALLO AL ACTUALIZAR PROSPECTO';
    }

} catch (PDOException $e) {
    error_log("PDOException en leads-update.php: " . $e->getMessage());
    $response['message'] = 'ERROR DE BASE DE DATOS';
} catch (Exception $e) {
    error_log("General Error en leads-update.php: " . $e->getMessage());
    $response['message'] = 'ERROR CRITICO';
}

if (ob_get_level() > 0) {
    ob_end_clean();
}
echo json_encode($response);
exit;
?>