<?php
session_start();

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

requirePermission('can_view_contracts');

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

    die("Contrato no encontrado");

}

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

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

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

    leads.full_name,
    leads.phone,
    leads.email,
    leads.document_type,
    leads.document_number

FROM contracts

LEFT JOIN leads
ON leads.id = contracts.lead_id

WHERE contracts.id = '$contract_id'

LIMIT 1
");

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

    die("Contrato no encontrado");

}

$contract =
$contractQuery->fetch_assoc();

/*
|--------------------------------------------------------------------------
| VALIDAR ACCESO JERARQUICO
|--------------------------------------------------------------------------
*/

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

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

    $visible_users =
    visibleUsersSql(
        $conn,
        intval($_SESSION['user_id'])
    );

    $visible_array =
    array_map(
        'intval',
        explode(
            ',',
            str_replace(
                "'",
                '',
                $visible_users
            )
        )
    );

    if(
        !in_array(
            intval($contract['assigned_user_id']),
            $visible_array
        )
    ){

        die("Acceso denegado");

    }

}

/*
|--------------------------------------------------------------------------
| PERMISO DE EDITAR
|--------------------------------------------------------------------------
*/

$can_edit_contract = false;

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

    $can_edit_contract = true;

}

/*
|--------------------------------------------------------------------------
| CAMPOS DINÁMICOS DEL CONTRATO + LEAD
|--------------------------------------------------------------------------
*/

$fields = $conn->query("
SELECT
    custom_fields.field_label,

    CASE

        WHEN contract_field_values.field_value IS NOT NULL
        AND contract_field_values.field_value != ''

        THEN contract_field_values.field_value

        ELSE lead_custom_values.field_value

    END as field_value

FROM custom_fields

LEFT JOIN contract_field_values
ON contract_field_values.field_id = custom_fields.id
AND contract_field_values.contract_id = '$contract_id'

LEFT JOIN lead_custom_values
ON lead_custom_values.field_id = custom_fields.id
AND lead_custom_values.lead_id = '".$contract['lead_id']."'

WHERE
(
    contract_field_values.id IS NOT NULL
    OR lead_custom_values.id IS NOT NULL
)

GROUP BY custom_fields.id

ORDER BY custom_fields.id ASC
");

/*
|--------------------------------------------------------------------------
| TIMELINE / LOGS
|--------------------------------------------------------------------------
*/

$logs = $conn->query("
SELECT
    contract_logs.*,
    users.name as user_name

FROM contract_logs

LEFT JOIN users
ON users.id = contract_logs.user_id

WHERE contract_logs.contract_id = '$contract_id'

ORDER BY contract_logs.id DESC
");

/*
|--------------------------------------------------------------------------
| NOTAS
|--------------------------------------------------------------------------
*/

$notes = $conn->query("
SELECT
    contract_notes.*,
    users.name as user_name

FROM contract_notes

LEFT JOIN users
ON users.id = contract_notes.user_id

WHERE contract_notes.contract_id = '$contract_id'

ORDER BY contract_notes.id DESC
");

?>

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

<head>

<meta charset="UTF-8">

<title>
Ver contrato
</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:#fff;
    border-radius:24px;
    padding:30px;
    margin-bottom:25px;
    box-shadow:0 10px 30px rgba(15,23,42,.06);
}

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

.info-box{
    background:#f8fafc;
    border-radius:18px;
    padding:20px;
}

.info-label{
    font-size:13px;
    color:#64748b;
    margin-bottom:8px;
}

.info-value{
    font-size:16px;
    font-weight:700;
    color:#02122c;
}

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

.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;
}

.timeline{
    position:relative;
    padding-left:30px;
}

.timeline:before{
    content:'';
    position:absolute;
    left:10px;
    top:0;
    width:2px;
    height:100%;
    background:#e2e8f0;
}

.timeline-item{
    position:relative;
    padding-bottom:30px;
}

.timeline-dot{
    position:absolute;
    left:-24px;
    top:5px;
    width:16px;
    height:16px;
    border-radius:999px;
    background:#4338ca;
}

.timeline-content{
    background:#f8fafc;
    border-radius:18px;
    padding:20px;
}

.timeline-title{
    font-size:15px;
    font-weight:700;
    color:#02122c;
    margin-bottom:8px;
}

.timeline-user{
    font-size:13px;
    color:#64748b;
    margin-bottom:8px;
}

.timeline-date{
    font-size:12px;
    color:#94a3b8;
}

.empty-timeline{
    color:#94a3b8;
    font-size:14px;
    text-align:center;
    padding:20px;
}

.notes-form{
    margin-bottom:30px;
}

.notes-textarea{
    width:100%;
    min-height:120px;
    border:none;
    background:#f8fafc;
    border-radius:18px;
    padding:20px;
    font-size:14px;
    resize:vertical;
    outline:none;
    box-sizing:border-box;
    margin-bottom:15px;
}

.save-note-btn{
    height:46px;
    padding:0 24px;
    border:none;
    border-radius:14px;
    background:#4338ca;
    color:#fff;
    font-size:14px;
    font-weight:700;
    cursor:pointer;
}

.note-item{
    background:#f8fafc;
    border-radius:18px;
    padding:20px;
    margin-bottom:18px;
}

.note-text{
    font-size:14px;
    color:#02122c;
    line-height:1.6;
    margin-bottom:14px;
}

.note-footer{
    display:flex;
    justify-content:space-between;
    align-items:center;
    gap:20px;
    flex-wrap:wrap;
}

.note-user{
    font-size:13px;
    color:#64748b;
    font-weight:700;
}

.note-date{
    font-size:12px;
    color:#94a3b8;
}

.empty-notes{
    text-align:center;
    padding:20px;
    color:#94a3b8;
    font-size:14px;
}

</style>

</head>

<body>

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

<div class="content-area">

    <a
        href="/pages/contracts.php"
        class="back-btn"
    >
        ← Volver a contratos
    </a>

    <div class="page-title">
        Contrato #<?= $contract['id'] ?>
    </div>

    <div class="page-subtitle">
        Información completa del contrato
    </div>

    <?php if($can_edit_contract): ?>

        <div style="display:flex;gap:12px;margin-bottom:25px;flex-wrap:wrap;">

            <a
                href="/pages/edit_contract.php?id=<?= $contract['id'] ?>"
                class="back-btn"
                style="background:#dcfce7;color:#166534;"
            >
                Editar contrato
            </a>

        </div>

    <?php endif; ?>

    <div class="white-card">

        <div class="info-grid">

            <div class="info-box">

                <div class="info-label">
                    Cliente
                </div>

                <div class="info-value">
                    <?= htmlspecialchars($contract['full_name'] ?? '') ?>
                </div>

            </div>

            <div class="info-box">

                <div class="info-label">
                    Documento
                </div>

                <div class="info-value">
                    <?= htmlspecialchars($contract['document_type'] ?? '') ?>
                    -
                    <?= htmlspecialchars($contract['document_number'] ?? '') ?>
                </div>

            </div>

            <div class="info-box">

                <div class="info-label">
                    Teléfono
                </div>

                <div class="info-value">
                    <?= htmlspecialchars($contract['phone'] ?? '') ?>
                </div>

            </div>

            <div class="info-box">

                <div class="info-label">
                    Correo
                </div>

                <div class="info-value">
                    <?= htmlspecialchars($contract['email'] ?? '') ?>
                </div>

            </div>

            <div class="info-box">

                <div class="info-label">
                    Estado actual
                </div>

                <div class="info-value">

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

                </div>

            </div>

            <div class="info-box">

                <div class="info-label">
                    Fecha creación
                </div>

                <div class="info-value">
                    <?= $contract['created_at'] ?>
                </div>

            </div>

        </div>

    </div>

    <div class="white-card">

        <div class="page-subtitle">
            Datos del contrato
        </div>

        <div class="info-grid">

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

                <div class="info-box">

                    <div class="info-label">
                        <?= htmlspecialchars((string)($field['field_label'] ?? '')) ?>
                    </div>

                    <div class="info-value">

<?php

$field_value =
(string)($field['field_value'] ?? '');

$file_extension =
strtolower(
    pathinfo(
        $field_value,
        PATHINFO_EXTENSION
    )
);

$is_image =
in_array(
    $file_extension,
    ['jpg','jpeg','png','gif','webp']
);

$is_file =
strpos($field_value,'/uploads/') !== false;

?>

<?php if($is_file): ?>

    <?php if($is_image): ?>

        <a
            href="<?= htmlspecialchars($field_value) ?>"
            target="_blank"
        >

            <img
                src="<?= htmlspecialchars($field_value) ?>"
                style="
                    width:100%;
                    max-width:260px;
                    border-radius:14px;
                    margin-top:10px;
                "
            >

        </a>

    <?php else: ?>

        <a
            href="<?= htmlspecialchars($field_value) ?>"
            target="_blank"
            style="
                display:inline-flex;
                align-items:center;
                justify-content:center;
                height:42px;
                padding:0 18px;
                background:#dbeafe;
                color:#1d4ed8;
                border-radius:12px;
                text-decoration:none;
                font-size:14px;
                font-weight:700;
            "
        >
            Ver archivo
        </a>

    <?php endif; ?>

<?php else: ?>

    <?= nl2br(htmlspecialchars($field_value)) ?>

<?php endif; ?>

                    </div>

                </div>

            <?php endwhile; ?>

        </div>

    </div>

    <div class="white-card">

        <div class="page-subtitle">
            Notas internas
        </div>

        <form
            action="/pages/save_note.php"
            method="POST"
            class="notes-form"
        >

            <input
                type="hidden"
                name="contract_id"
                value="<?= $contract_id ?>"
            >

            <textarea
                name="note"
                class="notes-textarea"
                placeholder="Escribe una nota interna..."
                required
            ></textarea>

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

        </form>

        <?php if($notes->num_rows > 0): ?>

            <?php while($note = $notes->fetch_assoc()): ?>

                <div class="note-item">

                    <div class="note-text">

                        <?= nl2br(
                            htmlspecialchars((string)($note['note_text'] ?? ''))
                        ) ?>

                    </div>

                    <div class="note-footer">

                        <div class="note-user">

                            <?= htmlspecialchars(
                                $note['user_name'] ?? 'Usuario'
                            ) ?>

                        </div>

                        <div class="note-date">

                            <?= date(
                                'd/m/Y H:i',
                                strtotime($note['created_at'])
                            ) ?>

                        </div>

                    </div>

                </div>

            <?php endwhile; ?>

        <?php else: ?>

            <div class="empty-notes">
                No hay notas registradas
            </div>

        <?php endif; ?>

    </div>

    <div class="white-card">

        <div class="page-subtitle">
            Historial del contrato
        </div>

        <?php if($logs->num_rows > 0): ?>

            <div class="timeline">

                <?php while($log = $logs->fetch_assoc()): ?>

                    <div class="timeline-item">

                        <div class="timeline-dot"></div>

                        <div class="timeline-content">

                            <div class="timeline-title">

                                <?= htmlspecialchars($log['old_status'] ?? '') ?>

                                →

                                <?= htmlspecialchars($log['new_status'] ?? '') ?>

                            </div>

                            <div class="timeline-user">

                                <?= htmlspecialchars(
                                    $log['user_name'] ?? 'Sistema'
                                ) ?>

                            </div>

                            <div class="timeline-date">

                                <?= date(
                                    'd/m/Y H:i',
                                    strtotime($log['created_at'])
                                ) ?>

                            </div>

                        </div>

                    </div>

                <?php endwhile; ?>

            </div>

        <?php else: ?>

            <div class="empty-timeline">
                Sin movimientos registrados
            </div>

        <?php endif; ?>

    </div>

</div>

</body>
</html>