<?php
session_start();

if(!isset($_SESSION['user_id'])){
    header("Location: /login.php");
    exit;
}

include("../config/db.php");
include("../includes/contract_helpers.php");

ensure_contract_schema($conn);

if(!isset($_GET['id'])){
    die("Lead no encontrado.");
}

$lead_id = intval($_GET['id']);
$user_id = intval($_SESSION['user_id']);

$lead_query = $conn->query("
    SELECT *
    FROM leads
    WHERE id = '$lead_id'
    LIMIT 1
");

if(!$lead_query || $lead_query->num_rows == 0){
    die("Lead invalido.");
}

$lead = $lead_query->fetch_assoc();
$existing_contract_id = contract_find_existing_by_lead($conn, $lead_id);

if($existing_contract_id > 0){
    header("Location: /pages/contract_view.php?id=$existing_contract_id");
    exit;
}

$user_query = $conn->query("
    SELECT *
    FROM users
    WHERE id = '$user_id'
    LIMIT 1
");

$user = $user_query && $user_query->num_rows > 0
? $user_query->fetch_assoc()
: [];

$customer_name = isset($lead['full_name']) && $lead['full_name'] != ''
? $lead['full_name']
: (isset($lead['name']) ? $lead['name'] : '');

$campaign_id = isset($lead['campaign_id']) && intval($lead['campaign_id']) > 0
? intval($lead['campaign_id'])
: (isset($user['campaign_id']) ? intval($user['campaign_id']) : 0);

$office_id = 0;

$user_office_query = $conn->query("
    SELECT office_id
    FROM user_offices
    WHERE user_id = '$user_id'
    LIMIT 1
");

if(
    $user_office_query
    &&
    $user_office_query->num_rows > 0
){

    $user_office =
    $user_office_query->fetch_assoc();

    $office_id =
    intval($user_office['office_id']);

}
$leader_id = isset($user['leader_id']) ? intval($user['leader_id']) : 0;
$status = 'Pendiente';

$stmt_contract = $conn->prepare("
    INSERT INTO contracts
    (
        customer_name,
        campaign_id,
        status,
        phone,
        created_by,
        office_id,
        advisor_id,
        leader_id,
        assigned_user_id,
        lead_id
    )
    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
");

$lead_phone = isset($lead['phone']) ? $lead['phone'] : '';

$stmt_contract->bind_param(
    "sissiiiiii",
    $customer_name,
    $campaign_id,
    $status,
    $lead_phone,
    $user_id,
    $office_id,
    $user_id,
    $leader_id,
    $user_id,
    $lead_id
);

if(!$stmt_contract->execute()){
    die("No se pudo convertir el lead.");
}

$contract_id = $stmt_contract->insert_id;

$fields = $conn->query("
    SELECT *
    FROM custom_fields
    WHERE module_name = 'contracts'
    ORDER BY id ASC
");

while($field = $fields->fetch_assoc()){
    $field_id = intval($field['id']);
    $field_name = strtolower($field['field_name']);
    $value = "";

    if(
        strpos($field_name, 'name') !== false
        || strpos($field_name, 'nombre') !== false
        || $field_name == 'full_name'
    ){
        $value = $customer_name;
    }

    if(
        strpos($field_name, 'phone') !== false
        || strpos($field_name, 'telefono') !== false
        || strpos($field_name, 'tel') !== false
    ){
        $value = isset($lead['phone']) ? $lead['phone'] : '';
    }

    if(
        strpos($field_name, 'email') !== false
        || strpos($field_name, 'correo') !== false
    ){
        $value = isset($lead['email']) ? $lead['email'] : '';
    }

    $stmt_value = $conn->prepare("
        INSERT INTO contract_field_values
        (
            contract_id,
            field_id,
            field_value
        )
        VALUES (?, ?, ?)
    ");

    $stmt_value->bind_param("iis", $contract_id, $field_id, $value);
    $stmt_value->execute();
}

$conn->query("
    UPDATE leads
    SET status_name = 'Convertido'
    WHERE id = '$lead_id'
");

$conn->query("
    INSERT INTO pipeline_status
    (
        contract_id,
        status_name
    )
    VALUES
    (
        '$contract_id',
        'Nuevo'
    )
");
$user_name = isset($_SESSION['user_name']) ? $_SESSION['user_name'] : 'Usuario';
contract_add_history($conn, $contract_id, "Contrato creado desde lead por $user_name");

header("Location: /pages/contract_edit.php?id=$contract_id");
exit;
?>
