<?php

function contract_column_exists($conn, $table, $column)
{
    $table = $conn->real_escape_string($table);
    $column = $conn->real_escape_string($column);

    $result = $conn->query("
        SHOW COLUMNS
        FROM `$table`
        LIKE '$column'
    ");

    return $result && $result->num_rows > 0;
}

function ensure_contract_schema($conn)
{
    if(!contract_column_exists($conn, 'contracts', 'lead_id')){
        $conn->query("ALTER TABLE contracts ADD COLUMN lead_id INT NULL");
    }

    if(!contract_column_exists($conn, 'contracts', 'status')){
        $conn->query("ALTER TABLE contracts ADD COLUMN status VARCHAR(100) DEFAULT 'Pendiente'");
    }

    if(!contract_column_exists($conn, 'contracts', 'customer_name')){
        $conn->query("ALTER TABLE contracts ADD COLUMN customer_name VARCHAR(255) NOT NULL DEFAULT ''");
    }

    if(!contract_column_exists($conn, 'contracts', 'amount')){
        $conn->query("ALTER TABLE contracts ADD COLUMN amount DECIMAL(10,2) DEFAULT 0.00");
    }

    if(!contract_column_exists($conn, 'contracts', 'created_by')){
        $conn->query("ALTER TABLE contracts ADD COLUMN created_by INT NULL");
    }

    if(!contract_column_exists($conn, 'contracts', 'assigned_user_id')){
        $conn->query("ALTER TABLE contracts ADD COLUMN assigned_user_id INT NULL");
    }
}

function contract_statuses()
{
    return [
        'Pendiente',
        'En revision',
        'Aprobado',
        'Rechazado',
        'Pagado'
    ];
}

function contract_file_types()
{
    return [
        'file',
        'image',
        'pdf',
        'audio',
        'document',
        'zip'
    ];
}

function is_contract_file_field($field_type)
{
    return in_array(trim($field_type), contract_file_types());
}

function contract_field_options($field)
{
    if(!isset($field['field_options']) || trim($field['field_options']) == ''){
        return [];
    }

    $raw = str_replace(["\r\n", "\r", "|"], "\n", $field['field_options']);
    $parts = preg_split('/[\n,]+/', $raw);
    $options = [];

    foreach($parts as $part){
        $value = trim($part);

        if($value != ''){
            $options[] = $value;
        }
    }

    return $options;
}

function contract_input_type($field_type)
{
    $field_type = trim($field_type);

    if($field_type == '' || $field_type == 'mask' || $field_type == 'phone'){
        return 'text';
    }

    if($field_type == 'currency'){
        return 'number';
    }

    if(in_array($field_type, ['email', 'date', 'number'])){
        return $field_type;
    }

    return 'text';
}

function contract_render_field_input($field, $value)
{
    $field_name = htmlspecialchars($field['field_name']);
    $field_label = htmlspecialchars($field['field_label']);
    $field_type = trim($field['field_type']);
    $required = !empty($field['is_required']) ? 'required' : '';
    $options = contract_field_options($field);

    echo '<div class="form-group">';
    echo '<label>' . $field_label . '</label>';

    if($field_type == 'textarea' || $field_type == 'textarea avanzada'){
        echo '<textarea name="' . $field_name . '" class="form-control" ' . $required . '>' . htmlspecialchars($value) . '</textarea>';
    } elseif($field_type == 'select') {
        echo '<select name="' . $field_name . '" class="form-control" ' . $required . '>';
        echo '<option value="">Seleccionar</option>';

        foreach($options as $option){
            $selected = ($option == $value) ? 'selected' : '';
            echo '<option value="' . htmlspecialchars($option) . '" ' . $selected . '>' . htmlspecialchars($option) . '</option>';
        }

        echo '</select>';
    } elseif($field_type == 'radio') {
        echo '<div class="option-list">';

        foreach($options as $option){
            $checked = ($option == $value) ? 'checked' : '';
            echo '<label class="option-item">';
            echo '<input type="radio" name="' . $field_name . '" value="' . htmlspecialchars($option) . '" ' . $checked . ' ' . $required . '>';
            echo '<span>' . htmlspecialchars($option) . '</span>';
            echo '</label>';
        }

        echo '</div>';
    } elseif($field_type == 'checkbox') {
        $selected_values = array_map('trim', explode(',', $value));
        echo '<div class="option-list">';

        foreach($options as $option){
            $checked = in_array($option, $selected_values) ? 'checked' : '';
            echo '<label class="option-item">';
            echo '<input type="checkbox" name="' . $field_name . '[]" value="' . htmlspecialchars($option) . '" ' . $checked . '>';
            echo '<span>' . htmlspecialchars($option) . '</span>';
            echo '</label>';
        }

        echo '</div>';
    } elseif(is_contract_file_field($field_type)) {
        echo '<input type="file" name="' . $field_name . '" class="form-control" ' . ($value == '' ? $required : '') . '>';

        if($value != ''){
            echo '<a href="/' . htmlspecialchars($value) . '" target="_blank" class="file-link">Ver archivo actual</a>';
        }
    } else {
        $input_type = contract_input_type($field_type);
        $step = $field_type == 'currency' ? 'step="0.01"' : '';

        echo '<input type="' . htmlspecialchars($input_type) . '" name="' . $field_name . '" class="form-control" value="' . htmlspecialchars($value) . '" ' . $step . ' ' . $required . '>';
    }

    echo '</div>';
}

function contract_post_value($field)
{
    $field_name = $field['field_name'];

    if($field['field_type'] == 'checkbox'){
        if(!isset($_POST[$field_name]) || !is_array($_POST[$field_name])){
            return '';
        }

        return implode(', ', array_map('trim', $_POST[$field_name]));
    }

    if(!isset($_POST[$field_name])){
        return '';
    }

    $value = trim($_POST[$field_name]);

    if($field['field_type'] == 'currency'){
        $value = str_replace(',', '.', $value);
    }

    return $value;
}

function contract_save_upload($field, $current_value, &$error)
{
    $field_name = $field['field_name'];

    if(!isset($_FILES[$field_name]) || $_FILES[$field_name]['name'] == ''){
        return $current_value;
    }

    if($_FILES[$field_name]['error'] != 0){
        $error = 'No se pudo subir el archivo de ' . $field['field_label'] . '.';
        return $current_value;
    }

    $max_size = 10 * 1024 * 1024;

    if($_FILES[$field_name]['size'] > $max_size){
        $error = 'El archivo de ' . $field['field_label'] . ' supera el limite de 10 MB.';
        return $current_value;
    }

    $original_name = $_FILES[$field_name]['name'];
    $extension = strtolower(pathinfo($original_name, PATHINFO_EXTENSION));
    $allowed_extensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'pdf', 'doc', 'docx', 'xls', 'xlsx', 'csv', 'txt', 'zip', 'mp3', 'wav', 'm4a'];

    if(!in_array($extension, $allowed_extensions)){
        $error = 'Tipo de archivo no permitido en ' . $field['field_label'] . '.';
        return $current_value;
    }

    $upload_dir = "../uploads/contracts/";

    if(!is_dir($upload_dir)){
        mkdir($upload_dir, 0777, true);
    }

    $new_name = date('YmdHis') . '_' . bin2hex(random_bytes(4)) . '.' . $extension;
    $target_file = $upload_dir . $new_name;

    if(!move_uploaded_file($_FILES[$field_name]['tmp_name'], $target_file)){
        $error = 'No se pudo guardar el archivo de ' . $field['field_label'] . '.';
        return $current_value;
    }

    return "uploads/contracts/" . $new_name;
}

function contract_add_history($conn, $contract_id, $text)
{
    $stmt = $conn->prepare("
        INSERT INTO contract_history
        (
            contract_id,
            action_text
        )
        VALUES (?, ?)
    ");

    $stmt->bind_param("is", $contract_id, $text);
    $stmt->execute();
}

function contract_user_can_access($conn, $contract, $user_id, $user_role)
{
    $user_role = strtolower($user_role);

    if($user_role == 'backoffice' || $user_role == 'admin'){
        return true;
    }

    if($user_role == 'asesor'){
        return intval($contract['advisor_id']) == $user_id || intval($contract['assigned_user_id']) == $user_id;
    }

    if($user_role == 'lider'){
        return intval($contract['leader_id']) == $user_id;
    }

    if($user_role == 'supervisor'){
        $office = $conn->query("
            SELECT office_id
            FROM users
            WHERE id = '$user_id'
            LIMIT 1
        ");

        if($office && $office->num_rows > 0){
            $office_data = $office->fetch_assoc();
            return intval($contract['office_id']) == intval($office_data['office_id']);
        }
    }

    return false;
}

function contract_find_existing_by_lead($conn, $lead_id)
{
    $stmt = $conn->prepare("
        SELECT id
        FROM contracts
        WHERE lead_id = ?
        LIMIT 1
    ");

    $stmt->bind_param("i", $lead_id);
    $stmt->execute();
    $stmt->bind_result($contract_id);

    if($stmt->fetch()){
        return intval($contract_id);
    }

    return 0;
}

?>
