<?php
session_start();

$user_role = (isset($_SESSION['is_admin']) && $_SESSION['is_admin'] == 1) ? 'admin' : 'user';

if(!isset($_SESSION['user_id'])){
    header("Location: /login.php");
    exit;
}

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

include("../includes/auth.php");
requirePermission('can_view_dashboard');
$user_id = $_SESSION['user_id'];
$user_role = (isset($_SESSION['is_admin']) && $_SESSION['is_admin'] == 1) ? 'admin' : 'user';

$filter_contracts = "";
$filter_activity = "";

/*
|--------------------------------------------------------------------------
| JERARQUÍA AUTOMÁTICA
|--------------------------------------------------------------------------
*/

$visible_users = [$user_id];

$pending = [$user_id];

while(!empty($pending)){

    $current = array_shift($pending);

    $children = $conn->query("
    SELECT id
    FROM users
    WHERE supervisor_id = '$current'
    ");

    while($child = $children->fetch_assoc()){

        $child_id = intval($child['id']);

        if(!in_array($child_id, $visible_users)){

            $visible_users[] = $child_id;
            $pending[] = $child_id;

        }

    }

}

$visible_ids =
implode(',', $visible_users);

$filter_contracts = "
WHERE assigned_user_id IN ($visible_ids)
";

$filter_activity = "";
$total_contracts = $conn->query("
SELECT COUNT(*) as total
FROM contracts
$filter_contracts
")->fetch_assoc()['total'];

$today_contracts = $conn->query("
SELECT COUNT(*) as total
FROM contracts
$filter_contracts
" . ($filter_contracts ? " AND " : " WHERE ") . "
DATE(created_at) = CURDATE()
")->fetch_assoc()['total'];

$month_contracts = $conn->query("
SELECT COUNT(*) as total
FROM contracts
$filter_contracts
" . ($filter_contracts ? " AND " : " WHERE ") . "
MONTH(created_at) = MONTH(CURRENT_DATE())
AND YEAR(created_at) = YEAR(CURRENT_DATE())
")->fetch_assoc()['total'];

$approved_contracts = $conn->query("
SELECT COUNT(*) as total
FROM contracts
$filter_contracts
" . ($filter_contracts ? " AND " : " WHERE ") . "
contract_status = 'Aprobado'
")->fetch_assoc()['total'];

$rejected_contracts = $conn->query("
SELECT COUNT(*) as total
FROM contracts
$filter_contracts
" . ($filter_contracts ? " AND " : " WHERE ") . "
contract_status = 'Rechazado'
")->fetch_assoc()['total'];

$active_pipeline = $conn->query("
SELECT COUNT(*) as total
FROM contracts
$filter_contracts
" . ($filter_contracts ? " AND " : " WHERE ") . "
contract_status != 'Cerrado'
")->fetch_assoc()['total'];

$recent_contracts = $conn->query("
SELECT *
FROM contracts
$filter_contracts
ORDER BY id DESC
LIMIT 5
");

$recent_activity = $conn->query("
SELECT *
FROM contract_history
$filter_activity
ORDER BY id DESC
LIMIT 8
");

$pipeline_data = [];

$stages = [
    'Nuevo',
    'Contactado',
    'Validacion',
    'Aprobado',
    'Rechazado',
    'Cerrado'
];

foreach($stages as $stage){

    $safe_stage =
    $conn->real_escape_string($stage);

    $count = $conn->query("
    SELECT COUNT(*) as total
    FROM contracts
    $filter_contracts
    " . ($filter_contracts ? " AND " : " WHERE ") . "
    contract_status = '$safe_stage'
    ")->fetch_assoc()['total'];

    $pipeline_data[$stage] = $count;

}

$conversion = 0;

if($total_contracts > 0){

    $conversion =
    round(
        ($approved_contracts / $total_contracts) * 100
    );

}

?>

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

<head>

<meta charset="UTF-8">

<title>
Dashboard
</title>

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

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

<style>

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

.page-header{
    margin-bottom:30px;
}

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

.page-subtitle{
    color:#6b7280;
    font-size:16px;
}

.stats-grid{
    display:grid;
    grid-template-columns:repeat(auto-fit,minmax(240px,1fr));
    gap:24px;
    margin-bottom:30px;
}

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

.stat-label{
    font-size:14px;
    color:#64748b;
    margin-bottom:12px;
    font-weight:600;
}

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

.dashboard-grid{
    display:grid;
    grid-template-columns:2fr 1fr;
    gap:24px;
    margin-bottom:30px;
}

.bottom-grid{
    display:grid;
    grid-template-columns:1.5fr 1fr;
    gap:24px;
}

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

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

.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;
    color:#02122c;
    font-size:14px;
}

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

.quick-stats{
    display:flex;
    flex-direction:column;
    gap:18px;
}

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

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

.quick-number{
    font-size:32px;
    font-weight:800;
    color:#02122c;
}

.activity-item{
    padding:14px 0;
    border-bottom:1px solid #edf0f5;
}

.activity-text{
    font-size:14px;
    color:#02122c;
    margin-bottom:6px;
    line-height:1.5;
}

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

canvas{
    max-height:340px;
}

@media(max-width:1200px){

    .dashboard-grid,
    .bottom-grid{
        grid-template-columns:1fr;
    }

}

</style>

</head>

<body>

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

<div class="content-area">

    <div class="page-header">

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

        <div class="page-subtitle">
            Resumen general del CRM y operaciones
        </div>

    </div>

    <div class="stats-grid">

        <div class="stat-card">

            <div class="stat-label">
                Total contratos
            </div>

            <div class="stat-number">
                <?= $total_contracts ?>
            </div>

        </div>

        <div class="stat-card">

            <div class="stat-label">
                Contratos hoy
            </div>

            <div class="stat-number">
                <?= $today_contracts ?>
            </div>

        </div>

        <div class="stat-card">

            <div class="stat-label">
                Pipeline activo
            </div>

            <div class="stat-number">
                <?= $active_pipeline ?>
            </div>

        </div>

        <div class="stat-card">

            <div class="stat-label">
                Conversión
            </div>

            <div class="stat-number">
                <?= $conversion ?>%
            </div>

        </div>

    </div>

    <div class="dashboard-grid">

        <div class="white-card">

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

            <canvas id="pipelineChart"></canvas>

        </div>

        <div class="white-card">

            <div class="card-title">
                Métricas rápidas
            </div>

            <div class="quick-stats">

                <div class="quick-box">

                    <div class="quick-label">
                        Aprobados
                    </div>

                    <div class="quick-number">
                        <?= $approved_contracts ?>
                    </div>

                </div>

                <div class="quick-box">

                    <div class="quick-label">
                        Rechazados
                    </div>

                    <div class="quick-number">
                        <?= $rejected_contracts ?>
                    </div>

                </div>

                <div class="quick-box">

                    <div class="quick-label">
                        Este mes
                    </div>

                    <div class="quick-number">
                        <?= $month_contracts ?>
                    </div>

                </div>

            </div>

        </div>

    </div>

    <div class="bottom-grid">

        <div class="white-card">

            <div class="card-title">
                Últimos contratos
            </div>

            <table class="crm-table">

                <thead>

                    <tr>

                        <th>ID</th>
                        <th>Fecha</th>
                        <th>Estado</th>

                    </tr>

                </thead>

                <tbody>

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

                        <tr>

                            <td>

                                <span class="badge">
                                    #<?= $contract['id'] ?>
                                </span>

                            </td>

                            <td>

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

                            </td>

                            <td>

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

                            </td>

                        </tr>

                    <?php endwhile; ?>

                </tbody>

            </table>

        </div>

        <div class="white-card">

            <div class="card-title">
                Actividad reciente
            </div>

            <?php while($activity = $recent_activity->fetch_assoc()): ?>

                <div class="activity-item">

                    <div class="activity-text">
                        <?= htmlspecialchars($activity['action_text']) ?>
                    </div>

                    <div class="activity-date">

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

                    </div>

                </div>

            <?php endwhile; ?>

        </div>

    </div>

</div>

<script>

const ctx =
document.getElementById('pipelineChart');

new Chart(ctx, {

    type: 'bar',

    data: {

        labels: <?= json_encode(array_keys($pipeline_data)) ?>,

        datasets: [{

            label: 'Contratos',

            data: <?= json_encode(array_values($pipeline_data)) ?>,

            borderWidth: 0,

            borderRadius: 12

        }]

    },

    options: {

        responsive: true,

        plugins: {

            legend: {
                display: false
            }

        },

        scales: {

            y: {
                beginAtZero: true
            }

        }

    }

});

</script>

</body>
</html>