<?php

session_start();

require_once("../includes/auth.php");

if(
    !isAdmin() &&
    (
        !isset($_SESSION['can_edit_contracts']) ||
        $_SESSION['can_edit_contracts'] != 1
    )
){

    die("No tienes permisos para editar contratos.");

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

if(!isset($_GET['id'])){

    die("Contrato no encontrado.");

}

$contract_id = intval($_GET['id']);

$contract_query = $conn->query("
SELECT *
FROM contracts
WHERE id = '$contract_id'
LIMIT 1
");

if(!$contract_query || $contract_query->num_rows == 0){

    die("Contrato inválido.");

}

$contract = $contract_query->fetch_assoc();

$campaign_id =
isset($contract['campaign_id'])
? intval($contract['campaign_id'])
: 0;

$error = "";

/*
|--------------------------------------------------------------------------
| CAMPOS DINÁMICOS
|--------------------------------------------------------------------------
*/

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

/*
|--------------------------------------------------------------------------
| VALORES ACTUALES
|--------------------------------------------------------------------------
*/

$field_values = [];

/*
|--------------------------------------------------------------------------
| VALORES DEL CONTRATO
|--------------------------------------------------------------------------
*/

$values_query = $conn->query("
SELECT *
FROM contract_field_values
WHERE contract_id = '$contract_id'
");

while($value = $values_query->fetch_assoc()){

    $field_values[$value['field_id']] =
    $value['field_value'];

}

/*
|--------------------------------------------------------------------------
| HEREDAR VALORES DEL LEAD
|--------------------------------------------------------------------------
*/

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

$lead_values = $conn->query("
SELECT *
FROM lead_custom_values
WHERE lead_id = '$lead_id'
");

while($lead_value = $lead_values->fetch_assoc()){

    $field_id =
    $lead_value['field_id'];

    /*
    |--------------------------------------------------------------------------
    | SOLO SI EL CONTRATO NO TIENE VALOR
    |--------------------------------------------------------------------------
    */

    if(
        !isset($field_values[$field_id])
        ||
        trim($field_values[$field_id]) == ''
    ){

        $field_values[$field_id] =
        $lead_value['field_value'];

    }

}

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

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

    $fields_update = $conn->query("
    SELECT *
    FROM custom_fields
    WHERE module_name = 'contracts'
    AND (
        campaign_id = '$campaign_id'
        OR campaign_id IS NULL
        OR campaign_id = 0
    )
    ");

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

        $field_id = $field['id'];

        $value =
        contract_post_value($field);

        /*
        |--------------------------------------------------------------------------
        | UPLOADS
        |--------------------------------------------------------------------------
        */

        if(is_contract_file_field($field['field_type'])){

            $current_value =
            isset($field_values[$field_id])
            ? $field_values[$field_id]
            : '';

            $value =
            contract_save_upload(
                $field,
                $current_value,
                $error
            );

        }

        /*
        |--------------------------------------------------------------------------
        | EXISTE VALOR
        |--------------------------------------------------------------------------
        */

        $check = $conn->query("
        SELECT id
        FROM contract_field_values
        WHERE contract_id = '$contract_id'
        AND field_id = '$field_id'
        LIMIT 1
        ");

        /*
        |--------------------------------------------------------------------------
        | UPDATE
        |--------------------------------------------------------------------------
        */

        if($check->num_rows > 0){

            $existing =
            $check->fetch_assoc();

            $value_id =
            $existing['id'];

            $stmt =
            $conn->prepare("
            UPDATE contract_field_values
            SET field_value = ?
            WHERE id = ?
            ");

            $stmt->bind_param(
                "si",
                $value,
                $value_id
            );

            $stmt->execute();

        }

        /*
        |--------------------------------------------------------------------------
        | INSERT
        |--------------------------------------------------------------------------
        */

        else {

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

            $stmt->bind_param(
                "iis",
                $contract_id,
                $field_id,
                $value
            );

            $stmt->execute();

        }

    }

    /*
    |--------------------------------------------------------------------------
    | HISTORIAL
    |--------------------------------------------------------------------------
    */

    $user_name =
    isset($_SESSION['user_name'])
    ? $_SESSION['user_name']
    : 'Usuario';

    if(function_exists('contract_add_history')){

        contract_add_history(
            $conn,
            $contract_id,
            "Contrato editado por " . $user_name
        );

    }

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

}

?>

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

<head>

<meta charset="UTF-8">

<title>
Editar contrato
</title>

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

<style>

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

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

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

.page-subtitle{
    color:#64748b;
    margin-bottom:30px;
}

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

.btn-save{
    margin-top:30px;
    height:52px;
    border:none;
    border-radius:14px;
    padding:0 24px;
    background:linear-gradient(90deg,#5b4bff,#7b61ff);
    color:#ffffff;
    font-size:15px;
    font-weight:700;
    cursor:pointer;
}

.error-box{
    background:#fee2e2;
    color:#991b1b;
    padding:16px;
    border-radius:14px;
    margin-bottom:20px;
    font-size:14px;
    font-weight:600;
}

.back-btn{
    display:inline-flex;
    align-items:center;
    justify-content:center;
    height:46px;
    padding:0 20px;
    border-radius:14px;
    background:#dbeafe;
    color:#1d4ed8;
    text-decoration:none;
    font-size:14px;
    font-weight:700;
    margin-bottom:25px;
}

</style>

</head>

<body>

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

<div class="content-area">

    <a
        href="/pages/contract_view.php?id=<?= $contract_id ?>"
        class="back-btn"
    >
        ← Volver al contrato
    </a>

    <div class="white-card">

        <div class="page-title">
            Editar contrato #<?= $contract_id ?>
        </div>

        <div class="page-subtitle">
            Modifica únicamente la información del contrato
        </div>

        <?php if(!empty($error)): ?>

            <div class="error-box">
                <?= htmlspecialchars($error) ?>
            </div>

        <?php endif; ?>

        <form
            method="POST"
            enctype="multipart/form-data"
        >

            <div class="form-grid">

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

                    <?php

                    $field_value =
                    isset($field_values[$field['id']])
                    ? $field_values[$field['id']]
                    : '';

                    ?>

                    <?php
                    contract_render_field_input(
                        $field,
                        $field_value
                    );
                    ?>

                <?php endwhile; ?>

            </div>

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

        </form>

    </div>

</div>

</body>
</html>