<?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);

$search = isset($_GET['search'])
? trim($_GET['search'])
: '';

$where_parts = [];
$user_id = intval($_SESSION['user_id']);
$user_role = strtolower($_SESSION['user_role']);

if($search != ''){

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

    $where_parts[] = "
    (
        contracts.id LIKE '%$safe_search%'
        OR contracts.created_at LIKE '%$safe_search%'
        OR EXISTS (
            SELECT 1
            FROM contract_field_values cfv
            WHERE
                cfv.contract_id = contracts.id
                AND cfv.field_value LIKE '%$safe_search%'
        )
    )
    ";

}

if($user_role == 'asesor'){

    $where_parts[] =
    "(contracts.advisor_id = '$user_id' OR contracts.assigned_user_id = '$user_id')";

} elseif($user_role == 'lider'){

    $where_parts[] =
    "contracts.leader_id = '$user_id'";

} elseif($user_role == 'supervisor'){

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

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

        $office = $userOffice->fetch_assoc();
        $office_id = intval($office['office_id']);

        $where_parts[] =
        "contracts.office_id = '$office_id'";

    }

}

$where =
count($where_parts) > 0
? "WHERE " . implode(" AND ", $where_parts)
: "";

$contracts = $conn->query("
SELECT *
FROM contracts
$where
ORDER BY id DESC
");

?>

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

<head>

<meta charset="UTF-8">

<title>
Listado de contratos
</title>

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

<style>

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

.page-header{
    display:flex;
    align-items:center;
    justify-content:space-between;
    margin-bottom:30px;
    gap:20px;
    flex-wrap:wrap;
}

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

.top-actions{
    display:flex;
    gap:15px;
    align-items:center;
}

.search-form{
    display:flex;
    gap:12px;
}

.search-box{
    width:360px;
    height:52px;
    border:none;
    background:#ffffff;
    border-radius:14px;
    padding:0 18px;
    font-size:15px;
    box-shadow:0 10px 30px rgba(15,23,42,.06);
}

.btn-search{
    height:52px;
    border:none;
    border-radius:14px;
    padding:0 22px;
    background:#02122c;
    color:#ffffff;
    font-size:14px;
    font-weight:700;
    cursor:pointer;
}

.btn-primary{
    height:52px;
    border:none;
    border-radius:14px;
    padding:0 24px;
    background:linear-gradient(90deg,#5b4bff,#7b61ff);
    color:#ffffff;
    font-size:15px;
    font-weight:600;
    cursor:pointer;
    text-decoration:none;
    display:flex;
    align-items:center;
}

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

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

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

.crm-table td{
    padding:20px 18px;
    border-bottom:1px solid #edf0f5;
    color:#02122c;
    font-size:14px;
    vertical-align:top;
}

.table-actions{
    display:flex;
    gap:10px;
    flex-wrap:wrap;
}

.btn-action{
    height:38px;
    padding:0 16px;
    border:none;
    border-radius:12px;
    font-size:13px;
    font-weight:600;
    cursor:pointer;
    text-decoration:none;
    display:flex;
    align-items:center;
}

.btn-view{
    background:#dbeafe;
    color:#1d4ed8;
}

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

.btn-delete{
    background:#fee2e2;
    color:#991b1b;
}

.empty-box{
    padding:60px;
    text-align:center;
    color:#6b7280;
    font-size:16px;
}

.field-item{
    margin-bottom:10px;
    line-height:1.5;
}

.file-link{
    color:#2563eb;
    font-weight:600;
    text-decoration:none;
}

</style>

</head>

<body>

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

<div class="content-area">

    <div class="page-header">

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

        <div class="top-actions">

            <form
                method="GET"
                class="search-form"
            >

                <input
                    type="text"
                    name="search"
                    class="search-box"
                    placeholder="Buscar nombre, DNI, campaña, correo, teléfono..."
                    value="<?= htmlspecialchars($search) ?>"
                >

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

            </form>

            <a
                href="/pages/contracts.php"
                class="btn-primary"
            >
                Nuevo contrato
            </a>

        </div>

    </div>

    <div class="white-card">

        <table class="crm-table">

            <thead>

                <tr>

                    <th>ID</th>
                    <th>Fecha</th>
                    <th>Información</th>
                    <th>Acciones</th>

                </tr>

            </thead>

            <tbody>

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

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

                    <?php

                    $contract_id = $contract['id'];

                    $fields = $conn->query("
                        SELECT
                            cf.field_label,
                            cf.field_type,
                            cfv.field_value
                        FROM contract_field_values cfv

                        INNER JOIN custom_fields cf
                        ON cf.id = cfv.field_id

                        WHERE cfv.contract_id = '$contract_id'
                    ");

                    ?>

                    <tr>

                        <td>
                            #<?= $contract_id ?>
                        </td>

                        <td>

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

                        </td>

                        <td>

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

                                <div class="field-item">

                                    <strong>
                                        <?= $field['field_label'] ?>:
                                    </strong>

                                    <?php if(

                                        in_array(
                                            $field['field_type'],
                                            [
                                                'file',
                                                'image',
                                                'pdf',
                                                'audio',
                                                'document',
                                                'zip'
                                            ]
                                        )

                                    ): ?>

                                        <?php if(!empty($field['field_value'])): ?>

                                            <a
                                                href="/<?= $field['field_value'] ?>"
                                                target="_blank"
                                                class="file-link"
                                            >
                                                Ver archivo
                                            </a>

                                        <?php endif; ?>

                                    <?php else: ?>

                                        <?= htmlspecialchars($field['field_value']) ?>

                                    <?php endif; ?>

                                </div>

                            <?php endwhile; ?>

                        </td>

                        <td>

                            <div class="table-actions">

                                <a
                                    href="/pages/contract_view.php?id=<?= $contract_id ?>"
                                    class="btn-action btn-view"
                                >
                                    Ver
                                </a>

                                <a
                                    href="/pages/contract_edit.php?id=<?= $contract_id ?>"
                                    class="btn-action btn-edit"
                                >
                                    Editar
                                </a>

                                <a
                                    href="/pages/delete_contract.php?id=<?= $contract_id ?>"
                                    class="btn-action btn-delete"
                                    onclick="return confirm('¿Eliminar contrato?')"
                                >
                                    Eliminar
                                </a>

                            </div>

                        </td>

                    </tr>

                <?php endwhile; ?>

            <?php else: ?>

                <tr>

                    <td colspan="4">

                        <div class="empty-box">
                            No se encontraron contratos.
                        </div>

                    </td>

                </tr>

            <?php endif; ?>

            </tbody>

        </table>

    </div>

</div>

</body>
</html>
