<?php
session_start();

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

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

$user_role =
strtolower($_SESSION['user_role']);

$whereContracts = "";

if($user_role == 'asesor'){

    $whereContracts =
    "AND advisor_id = '$user_id'";

}

elseif($user_role == 'lider'){

    $whereContracts =
    "AND leader_id = '$user_id'";

}

elseif($user_role == 'supervisor'){

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

    $office =
    $officeQuery->fetch_assoc();

    $office_id =
    intval($office['office_id']);

    $whereContracts =
    "AND office_id = '$office_id'";

}

/*
|--------------------------------------------------------------------------
| CAMBIAR ESTADO
|--------------------------------------------------------------------------
*/

if(
    $_SERVER['REQUEST_METHOD'] == 'POST' &&
    isset($_POST['contract_id'])
){

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

    $new_status =
    trim($_POST['new_status']);

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

    $stmt->bind_param(
        "si",
        $new_status,
        $contract_id
    );

    $stmt->execute();

    header("Location: contracts_pipeline.php");
    exit;

}

/*
|--------------------------------------------------------------------------
| CAMPAÑAS
|--------------------------------------------------------------------------
*/

$campaigns = $conn->query("
SELECT *
FROM campaigns
ORDER BY campaign_name ASC
");

?>

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

<head>

<meta charset="UTF-8">

<title>
Pipeline contratos
</title>

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

<style>

body{
    background:#f1f5f9;
}

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

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

.pipeline-wrapper{
    display:flex;
    gap:20px;
    overflow-x:auto;
    align-items:flex-start;
    padding-bottom:20px;
}

.pipeline-column{
    min-width:340px;
    background:#ffffff;
    border-radius:22px;
    padding:20px;
    box-shadow:0 10px 25px rgba(15,23,42,.06);
}

.column-title{
    font-size:18px;
    font-weight:800;
    color:#02122c;
    margin-bottom:18px;
    display:flex;
    justify-content:space-between;
    align-items:center;
}

.contract-count{
    background:#ede9fe;
    color:#5b21b6;
    padding:6px 10px;
    border-radius:10px;
    font-size:12px;
    font-weight:700;
}

.contract-card{
    background:#f8fafc;
    border-radius:18px;
    padding:18px;
    margin-bottom:15px;
    border:1px solid #e2e8f0;
    display:flex;
    flex-direction:column;
}

.contract-card.priority{
    border:2px solid #f59e0b;
    background:#fff7ed;
}

.contract-name{
    font-size:16px;
    font-weight:800;
    color:#02122c;
    margin-bottom:8px;
}

.contract-meta{
    font-size:13px;
    color:#64748b;
    margin-bottom:6px;
}

.status-select{
    width:100%;
    margin-top:14px;
    height:46px;
    border:none;
    background:#e2e8f0;
    border-radius:12px;
    padding:0 14px;
}

.view-btn{
    margin-top:14px;
    display:inline-block;
    padding:10px 14px;
    background:#dbeafe;
    color:#1d4ed8;
    border-radius:10px;
    text-decoration:none;
    font-size:13px;
    font-weight:700;
    text-align:center;
}

.empty-box{
    padding:16px;
    border-radius:14px;
    background:#f8fafc;
    color:#64748b;
    font-size:14px;
}

.priority-alert{
    margin-top:10px;
    background:#fef3c7;
    color:#92400e;
    border-radius:10px;
    padding:10px;
    font-size:12px;
    font-weight:700;
}

</style>

</head>

<body>

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

<div class="content-area">

    <div class="page-title">
        Pipeline de contratos
    </div>

    <div class="pipeline-wrapper">

        <?php while($campaign = $campaigns->fetch_assoc()): ?>

            <?php

            $campaign_id =
            intval($campaign['id']);

            $statuses = $conn->query("
            SELECT *
            FROM campaign_statuses
            WHERE campaign_id = '$campaign_id'
            ORDER BY id ASC
            ");

            ?>

            <?php while($status = $statuses->fetch_assoc()): ?>

                <?php

                $status_name =
                $status['status_name'];

                /*
                |--------------------------------------------------------------------------
                | EL MÁS VIEJO ARRIBA
                |--------------------------------------------------------------------------
                */

                $contracts = $conn->query("
                SELECT *
                FROM contracts
                WHERE status = '$status_name'
                AND campaign_id = '$campaign_id'
                $whereContracts
                ORDER BY created_at ASC, id ASC
                ");

                $contracts_count =
                $contracts->num_rows;

                ?>

                <div class="pipeline-column">

                    <div class="column-title">

                        <span>
                            <?= htmlspecialchars($status_name) ?>
                        </span>

                        <span class="contract-count">
                            <?= $contracts_count ?>
                        </span>

                    </div>

                    <?php if($contracts_count > 0): ?>

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

                            <?php

                            $advisor_name = "-";

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

                            $advisor = $conn->query("
                            SELECT name
                            FROM users
                            WHERE id = '$advisor_id'
                            LIMIT 1
                            ");

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

                                $advisorData =
                                $advisor->fetch_assoc();

                                $advisor_name =
                                $advisorData['name'];

                            }

                            $created_time =
                            strtotime($contract['created_at']);

                            $hours_waiting =
                            floor(
                                (time() - $created_time) / 3600
                            );

                            $priority_class = "";

                            if($hours_waiting >= 12){

                                $priority_class =
                                "priority";

                            }

                            ?>

                            <div class="contract-card <?= $priority_class ?>">

                                <div class="contract-name">

                                    <?= htmlspecialchars($contract['customer_name']) ?>

                                </div>

                                <div class="contract-meta">

                                    Contrato #<?= $contract['id'] ?>

                                </div>

                                <div class="contract-meta">

                                    Asesor:
                                    <?= htmlspecialchars($advisor_name) ?>

                                </div>

                                <div class="contract-meta">

                                    Campaña:
                                    <?= htmlspecialchars($campaign['campaign_name']) ?>

                                </div>

                                <div class="contract-meta">

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

                                </div>

                                <?php if($hours_waiting >= 12): ?>

                                    <div class="priority-alert">

                                        Lleva <?= $hours_waiting ?> horas sin gestión

                                    </div>

                                <?php endif; ?>

                                <form method="POST">

                                    <input
                                        type="hidden"
                                        name="contract_id"
                                        value="<?= $contract['id'] ?>"
                                    >

                                    <select
                                        name="new_status"
                                        class="status-select"
                                        onchange="this.form.submit()"
                                    >

                                        <?php

                                        $allStatuses = $conn->query("
                                        SELECT *
                                        FROM campaign_statuses
                                        WHERE campaign_id = '$campaign_id'
                                        ORDER BY id ASC
                                        ");

                                        while($statusOption = $allStatuses->fetch_assoc()):

                                        ?>

                                            <option
                                                value="<?= htmlspecialchars($statusOption['status_name']) ?>"
                                                <?= $statusOption['status_name'] == $contract['status'] ? 'selected' : '' ?>
                                            >

                                                <?= htmlspecialchars($statusOption['status_name']) ?>

                                            </option>

                                        <?php endwhile; ?>

                                    </select>

                                </form>

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

                            </div>

                        <?php endwhile; ?>

                    <?php else: ?>

                        <div class="empty-box">

                            No hay contratos

                        </div>

                    <?php endif; ?>

                </div>

            <?php endwhile; ?>

        <?php endwhile; ?>

    </div>

</div>

</body>
</html>