<?php

session_start();

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

requirePermission('can_view_contracts');
/*
|--------------------------------------------------------------------------
| CREAR TABLAS
|--------------------------------------------------------------------------
*/

$conn->query("
CREATE TABLE IF NOT EXISTS contracts (
    id INT AUTO_INCREMENT PRIMARY KEY,
    lead_id INT NOT NULL,
    campaign_id INT NULL,
    contract_status VARCHAR(100) DEFAULT 'Pendiente',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
");

$conn->query("
CREATE TABLE IF NOT EXISTS contract_field_values (
    id INT AUTO_INCREMENT PRIMARY KEY,
    contract_id INT NOT NULL,
    field_id INT NOT NULL,
    field_value LONGTEXT,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
");

/*
|--------------------------------------------------------------------------
| VALIDAR COLUMNAS USERS
|--------------------------------------------------------------------------
*/

$columns = [

    'can_edit_contracts',
    'can_export_contracts'

];

foreach($columns as $column){

    $check = $conn->query("
    SHOW COLUMNS
    FROM users
    LIKE '$column'
    ");

    if($check->num_rows == 0){

        $conn->query("
        ALTER TABLE users
        ADD COLUMN $column TINYINT(1) DEFAULT 0
        ");

    }

}

/*
|--------------------------------------------------------------------------
| VALIDAR COLUMNAS CONTRACTS
|--------------------------------------------------------------------------
*/

$contract_columns = [

    'contract_status' =>
    "ALTER TABLE contracts ADD COLUMN contract_status VARCHAR(100) DEFAULT 'Pendiente'",

    'campaign_id' =>
    "ALTER TABLE contracts ADD COLUMN campaign_id INT NULL",

    'assigned_user_id' =>
    "ALTER TABLE contracts ADD COLUMN assigned_user_id INT NULL"

];

foreach($contract_columns as $column => $sql){

    $check = $conn->query("
    SHOW COLUMNS
    FROM contracts
    LIKE '$column'
    ");

    if($check->num_rows == 0){

        $conn->query($sql);

    }

}

/*
|--------------------------------------------------------------------------
| ACTUALIZAR SESSION DE PERMISOS
|--------------------------------------------------------------------------
*/

if(isset($_SESSION['user_id'])){

    $session_user_id =
    intval($_SESSION['user_id']);

    $permissionQuery = $conn->query("
    SELECT
        can_edit_contracts,
        can_export_contracts
    FROM users
    WHERE id = '$session_user_id'
    LIMIT 1
    ");

    if($permissionQuery->num_rows > 0){

        $permissionUser =
        $permissionQuery->fetch_assoc();

        $_SESSION['can_edit_contracts'] =
        $permissionUser['can_edit_contracts'];

        $_SESSION['can_export_contracts'] =
        $permissionUser['can_export_contracts'];

    }

}

/*
|--------------------------------------------------------------------------
| LEAD
|--------------------------------------------------------------------------
*/

$lead_id = 0;

$lead = null;

if(isset($_GET['lead_id'])){

    $lead_id =
    intval($_GET['lead_id']);

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

    if($leadQuery->num_rows > 0){

    $lead =
    $leadQuery->fetch_assoc();

    /*
    |--------------------------------------------------------------------------
    | VALIDAR ACCESO AL LEAD
    |--------------------------------------------------------------------------
    */

    $logged_user_id =
    intval($_SESSION['user_id']);

    if(
    isset($lead['assigned_user_id'])
    &&
    $lead['assigned_user_id'] != NULL
    &&
    $lead['assigned_user_id'] != 0
    &&
    !isset($_SESSION['can_manage_users'])
){

    $logged_user_id =
    intval($_SESSION['user_id']);

    if($lead['assigned_user_id'] != $logged_user_id){

        die("Acceso denegado");

    }

}

} else {

        $lead = null;

    }

} else {

    $lead = null;

}

/*
|--------------------------------------------------------------------------
| CAMPAÑA DEL LEAD
|--------------------------------------------------------------------------
*/

$campaign_id = 0;

if($lead && isset($lead['campaign_id'])){

    $campaign_id =
    intval($lead['campaign_id']);

}

/*
|--------------------------------------------------------------------------
| CAMPOS PERSONALIZADOS
|--------------------------------------------------------------------------
*/

$custom_fields = $conn->query("
SELECT *
FROM custom_fields
WHERE
(
    module_name = 'contracts'
    OR module_name = 'leads'
)
AND (
    campaign_id = '$campaign_id'
    OR campaign_id IS NULL
    OR campaign_id = 0
)
ORDER BY id ASC
");
/*
|--------------------------------------------------------------------------
| GUARDAR CONTRATO
|--------------------------------------------------------------------------
*/

if($_SERVER['REQUEST_METHOD'] === 'POST'){

    $lead_id =
    intval($_POST['lead_id']);

    /*
    |--------------------------------------------------------------------------
    | OBTENER CAMPAÑA DEL LEAD
    |--------------------------------------------------------------------------
    */

    $lead_campaign = 0;

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

    if($leadCampaignQuery->num_rows > 0){

        $leadCampaignData =
        $leadCampaignQuery->fetch_assoc();

        $lead_campaign =
        intval($leadCampaignData['campaign_id']);

    }

    /*
    |--------------------------------------------------------------------------
    | ESTADO INICIAL
    |--------------------------------------------------------------------------
    */

    $default_status = 'Pendiente';

    $statusQuery = $conn->query("
    SELECT status_name
    FROM campaign_statuses
    WHERE campaign_id = '$lead_campaign'
    ORDER BY id ASC
    LIMIT 1
    ");

    if($statusQuery->num_rows > 0){

        $statusData =
        $statusQuery->fetch_assoc();

        $default_status =
        $statusData['status_name'];

    }

    /*
    |--------------------------------------------------------------------------
    | INSERTAR CONTRATO
    |--------------------------------------------------------------------------
    */

    $insertContract =
    $conn->prepare("
    INSERT INTO contracts
(
    lead_id,
    campaign_id,
    contract_status,
    assigned_user_id
)
VALUES
(
    ?, ?, ?, ?
)
    ");

    $assigned_user_id =
intval($_SESSION['user_id']);

$insertContract->bind_param(
    "iisi",
    $lead_id,
    $lead_campaign,
    $default_status,
    $assigned_user_id
);

    if($insertContract->execute()){

        $contract_id =
        $insertContract->insert_id;

        /*
        |--------------------------------------------------------------------------
        | GUARDAR CAMPOS
        |--------------------------------------------------------------------------
        */

        $fieldsQuery = $conn->query("
        SELECT *
        FROM custom_fields
        WHERE module_name = 'contracts'
        ");

        while($field = $fieldsQuery->fetch_assoc()){

            $field_id =
            $field['id'];

            $field_key =
            'field_'.$field_id;

            $field_value =
            isset($_POST[$field_key])
            ? trim($_POST[$field_key])
            : '';

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

            $saveField->bind_param(
                "iis",
                $contract_id,
                $field_id,
                $field_value
            );

            $saveField->execute();

        }

        // Insertar el primer estado configurado para esta campana
        $first_stage = 'Nuevo';
        $stage_q = $conn->query("SELECT status_name FROM campaign_statuses WHERE campaign_id='$lead_campaign' ORDER BY id ASC LIMIT 1");
        if($stage_q && $stage_q->num_rows > 0) $first_stage = $stage_q->fetch_assoc()['status_name'];
        $fs = $conn->real_escape_string($first_stage);
        $conn->query("INSERT INTO pipeline_status (contract_id, status_name) VALUES ('$contract_id','$fs')");

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

    }

}

/*
|--------------------------------------------------------------------------
| FILTROS
|--------------------------------------------------------------------------
*/

$search = '';

$date_from = '';

$date_to = '';

if(isset($_GET['search'])){

    $search =
    trim($_GET['search']);

}

if(isset($_GET['date_from'])){

    $date_from =
    trim($_GET['date_from']);

}

if(isset($_GET['date_to'])){

    $date_to =
    trim($_GET['date_to']);

}

$where_conditions = [];

/*
|--------------------------------------------------------------------------
| FILTRO JERARQUICO
|--------------------------------------------------------------------------
*/

if(
    !isset($_SESSION['can_manage_users'])
    ||
    $_SESSION['can_manage_users'] != 1
){

    $logged_user_id =
    intval($_SESSION['user_id']);

    include("../includes/hierarchy.php");

    $visible_users =
    implode(',', getVisibleUsers(
        $conn,
        $logged_user_id
    ));

    $where_conditions[] =
    "contracts.assigned_user_id IN ($visible_users)";

}
$logged_user_id =
intval($_SESSION['user_id']);



if($search != ''){

    $search_safe =
    $conn->real_escape_string($search);

    $where_conditions[] = "
    (
        leads.full_name LIKE '%$search_safe%'
        OR leads.document_number LIKE '%$search_safe%'
        OR leads.phone LIKE '%$search_safe%'
        OR contracts.id LIKE '%$search_safe%'
    )
    ";

}

if($date_from != ''){

    $date_from_safe =
    $conn->real_escape_string($date_from);

    $where_conditions[] = "
    DATE(contracts.created_at) >= '$date_from_safe'
    ";

}

if($date_to != ''){

    $date_to_safe =
    $conn->real_escape_string($date_to);

    $where_conditions[] = "
    DATE(contracts.created_at) <= '$date_to_safe'
    ";

}

// FILTRO DESACTIVADO TEMPORALMENTE

$where_sql = '';

if(count($where_conditions) > 0){

    $where_sql =
    'WHERE '.implode(' AND ', $where_conditions);

}

/*
|--------------------------------------------------------------------------
| CONTRATOS
|--------------------------------------------------------------------------
*/

$contracts = $conn->query("
SELECT
    contracts.*,

    leads.full_name,
    leads.assigned_user_id,
    leads.phone,
    leads.document_number,

    campaigns.campaign_name,

    lead_campaigns.campaign_name AS lead_campaign_name

FROM contracts

LEFT JOIN leads
ON leads.id = contracts.lead_id

LEFT JOIN campaigns
ON campaigns.id = contracts.campaign_id

LEFT JOIN campaigns AS lead_campaigns
ON lead_campaigns.id = leads.campaign_id

$where_sql

ORDER BY contracts.id DESC
");

?>

<!DOCTYPE html>
<html lang="es">

<head>

<meta charset="UTF-8">

<title>
Contratos
</title>

<link rel="stylesheet" href="/assets/css/style.css">

<style>

.content-area{
    margin-left:260px;
    padding:40px;
}

.page-title{
    font-size:42px;
    font-weight:800;
    color:#02122c;
    margin-bottom:10px;
}

.page-subtitle{
    color:#6b7280;
    margin-bottom:30px;
}

.white-card{
    background:#ffffff;
    border-radius:24px;
    padding:30px;
    margin-bottom:25px;
    box-shadow:0 10px 30px rgba(15,23,42,.06);
}

.form-grid{
    display:grid;
    grid-template-columns:repeat(auto-fit,minmax(250px,1fr));
    gap:20px;
}

.form-group{
    display:flex;
    flex-direction:column;
}

.form-group label{
    margin-bottom:10px;
    font-size:14px;
    font-weight:700;
    color:#475569;
}

.form-control{
    height:52px;
    border:none;
    background:#f3f5fa;
    border-radius:14px;
    padding:0 16px;
    font-size:15px;
}

.btn-save{
    margin-top:25px;
    height:52px;
    border:none;
    border-radius:14px;
    padding:0 24px;
    background:linear-gradient(90deg,#5b4bff,#7b61ff);
    color:#fff;
    font-weight:700;
    cursor:pointer;
    text-decoration:none;
    display:inline-flex;
    align-items:center;
    justify-content:center;
}

.export-btn{
    background:linear-gradient(90deg,#059669,#10b981);
}

.crm-table{
    width:100%;
    border-collapse:collapse;
}

.crm-table th{
    text-align:left;
    padding:16px;
    font-size:13px;
    text-transform:uppercase;
    color:#7b8190;
    border-bottom:1px solid #edf0f5;
}

.crm-table td{
    padding:18px 16px;
    border-bottom:1px solid #edf0f5;
}

.badge{
    display:inline-flex;
    align-items:center;
    justify-content:center;
    height:32px;
    padding:0 14px;
    border-radius:999px;
    background:#eef2ff;
    color:#4338ca;
    font-size:12px;
    font-weight:700;
}

.view-btn{
    display:inline-flex;
    align-items:center;
    justify-content:center;
    height:38px;
    padding:0 16px;
    border-radius:12px;
    background:#dbeafe;
    color:#1d4ed8;
    text-decoration:none;
    font-size:13px;
    font-weight:700;
}

.edit-btn{
    background:#dcfce7;
    color:#166534;
}

.lead-box{
    background:#f8fafc;
    border-radius:18px;
    padding:20px;
    margin-bottom:25px;
}

.lead-title{
    font-size:18px;
    font-weight:800;
    color:#02122c;
    margin-bottom:10px;
}

.lead-info{
    color:#475569;
    line-height:1.8;
}

.actions-row{
    display:flex;
    gap:10px;
    align-items:center;
    flex-wrap:wrap;
    margin-top:25px;
}

.campaign-badge{
    display:inline-flex;
    align-items:center;
    justify-content:center;
    height:32px;
    padding:0 14px;
    border-radius:999px;
    background:#ecfeff;
    color:#155e75;
    font-size:12px;
    font-weight:700;
}

</style>

</head>

<body>

<?php include("../includes/sidebar.php"); ?>

<div class="content-area">

    <div class="page-title">
        Contratos
    </div>

    <div class="page-subtitle">
        Gestión de contratos del CRM
    </div>

    <div class="white-card">

        <form method="GET">

            <div class="form-grid">

                <div class="form-group">

                    <label>
                        Buscar contrato
                    </label>

                    <input
                        type="text"
                        name="search"
                        class="form-control"
                        placeholder="Nombre, documento, teléfono o ID"
                        value="<?= htmlspecialchars($search ?? '') ?>"
                    >

                </div>

                <div class="form-group">

                    <label>
                        Fecha desde
                    </label>

                    <input
                        type="date"
                        name="date_from"
                        class="form-control"
                        value="<?= htmlspecialchars($date_from ?? '') ?>"
                    >

                </div>

                <div class="form-group">

                    <label>
                        Fecha hasta
                    </label>

                    <input
                        type="date"
                        name="date_to"
                        class="form-control"
                        value="<?= htmlspecialchars($date_to ?? '') ?>"
                    >

                </div>

            </div>

            <div class="actions-row">

                <button
                    type="submit"
                    class="btn-save"
                >
                    Buscar
                </button>

                <?php if(
                    isset($_SESSION['can_export_contracts']) &&
                    $_SESSION['can_export_contracts'] == 1
                ): ?>

                    <a
                        href="/pages/export_contracts.php?search=<?= urlencode($search) ?>&date_from=<?= urlencode($date_from) ?>&date_to=<?= urlencode($date_to) ?>"
                        class="btn-save export-btn"
                    >
                        Exportar CSV
                    </a>

                <?php endif; ?>

            </div>

        </form>

    </div>

    <?php if($lead): ?>

        <div class="white-card">

            <div class="lead-box">

                <div class="lead-title">
                    Cliente seleccionado
                </div>

                <div class="lead-info">

                    <strong>Documento:</strong>

                    <?= htmlspecialchars($lead['document_type'] ?? '') ?>
                    -
                    <?= htmlspecialchars($lead['document_number'] ?? '') ?>

                    <br>

                    <strong>Nombre:</strong>

                    <?= htmlspecialchars($lead['full_name'] ?? '') ?>

                    <br>

                    <strong>Teléfono:</strong>

                    <?= htmlspecialchars($lead['phone'] ?? '') ?>

                </div>

            </div>

            <form method="POST">

                <input
                    type="hidden"
                    name="lead_id"
                    value="<?= $lead['id'] ?>"
                >

                <div class="form-grid">

                    <?php while($field = $custom_fields->fetch_assoc()): ?>

<?php

$default_value = '';

$field_label =
strtolower(trim($field['field_label']));

/*
|--------------------------------------------------------------------------
| DATOS PRINCIPALES
|--------------------------------------------------------------------------
*/

if(
    strpos($field_label,'nombre') !== false
){

    $default_value =
    $lead['full_name'] ?? '';

}

elseif(
    strpos($field_label,'documento') !== false
    ||
    strpos($field_label,'dni') !== false
    ||
    strpos($field_label,'cedula') !== false
    ||
    strpos($field_label,'cédula') !== false
){

    $default_value =
    $lead['document_number'] ?? '';

}

elseif(
    strpos($field_label,'telefono') !== false
    ||
    strpos($field_label,'teléfono') !== false
    ||
    strpos($field_label,'celular') !== false
){

    $default_value =
    $lead['phone'] ?? '';

}

elseif(
    strpos($field_label,'email') !== false
    ||
    strpos($field_label,'correo') !== false
){

    $default_value =
    $lead['email'] ?? '';

}

/*
|--------------------------------------------------------------------------
| CAMPOS PERSONALIZADOS DEL LEAD
|--------------------------------------------------------------------------
*/

$lead_custom = $conn->query("
SELECT
    lead_custom_values.field_value
FROM lead_custom_values

INNER JOIN custom_fields
ON custom_fields.id = lead_custom_values.field_id

WHERE lead_custom_values.lead_id = '".$lead['id']."'
AND LOWER(custom_fields.field_label) = '".$conn->real_escape_string($field_label)."'

LIMIT 1
");

if($lead_custom->num_rows > 0){

    $lead_custom_data =
    $lead_custom->fetch_assoc();

    if(
        !empty($lead_custom_data['field_value'])
    ){

        $default_value =
        $lead_custom_data['field_value'];

    }

}

?>

<div class="form-group">

<label>
<?= htmlspecialchars($field['field_label'] ?? '') ?>
</label>

<?php if($field['field_type'] == 'textarea'): ?>

<textarea
    name="field_<?= $field['id'] ?>"
    class="form-control"
    style="height:120px;padding-top:15px;"
><?= htmlspecialchars($default_value) ?></textarea>

<?php elseif($field['field_type'] == 'file'): ?>

<?php if($default_value != ''): ?>

<a
    href="<?= htmlspecialchars($default_value) ?>"
    target="_blank"
    class="view-btn"
    style="margin-bottom:10px;"
>
    Ver archivo actual
</a>

<?php endif; ?>

<input
    type="file"
    name="field_<?= $field['id'] ?>"
    class="form-control"
>

<?php elseif($field['field_type'] == 'select'): ?>

<select
    name="field_<?= $field['id'] ?>"
    class="form-control"
>

<option value="">
Seleccionar
</option>

<?php

$options =
explode(
    ',',
    $field['field_options']
);

foreach($options as $option):

$option = trim($option);

?>

<option
    value="<?= htmlspecialchars($option) ?>"
    <?= $default_value == $option ? 'selected' : '' ?>
>
    <?= htmlspecialchars($option) ?>
</option>

<?php endforeach; ?>

</select>

<?php else: ?>

<input
    type="<?= htmlspecialchars($field['field_type']) ?>"
    name="field_<?= $field['id'] ?>"
    class="form-control"
    value="<?= htmlspecialchars($default_value) ?>"
>

<?php endif; ?>

</div>

<?php endwhile; ?>

                </div>

                <button
                    type="submit"
                    class="btn-save"
                >
                    Guardar contrato
                </button>

            </form>

        </div>

    <?php endif; ?>

    <div class="white-card">

        <table class="crm-table">

            <thead>

                <tr>

                    <th>ID</th>
                    <th>Campaña</th>
                    <th>Cliente</th>
                    <th>Documento</th>
                    <th>Teléfono</th>
                    <th>Estado</th>
                    <th>Fecha</th>
                    <th>Acciones</th>

                </tr>

            </thead>

            <tbody>

                <?php while($contract = $contracts->fetch_assoc()): ?>

                    <tr>

                        <td>
                            #<?= $contract['id'] ?>
                        </td>

                        <td>

                            <span class="campaign-badge">
                                <?= htmlspecialchars(
    $contract['campaign_name']
    ??
    $contract['lead_campaign_name']
    ??
    'Sin campaña'
) ?>
                            </span>

                        </td>

                        <td>
                            <?= htmlspecialchars($contract['full_name'] ?? '') ?>
                        </td>

                        <td>
                            <?= htmlspecialchars($contract['document_number'] ?? '') ?>
                        </td>

                        <td>
                            <?= htmlspecialchars($contract['phone'] ?? '') ?>
                        </td>

                        <td>

                            <span class="badge">
                                <?= htmlspecialchars($contract['contract_status'] ?? '') ?>
                            </span>

                        </td>

                        <td>
                            <?= $contract['created_at'] ?>
                        </td>

                        <td>

                            <div style="display:flex;gap:10px;flex-wrap:wrap;">

                                <a
                                    href="/pages/contract_view.php?id=<?= $contract['id'] ?>"
                                    class="view-btn"
                                >
                                    Ver
                                </a>

                                <!-- EDICION DESACTIVADA -->
                            </div>

                        </td>

                    </tr>

                <?php endwhile; ?>

            </tbody>

        </table>

    </div>

</div>

</body>
</html>