<?php

session_start();

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

/*
|--------------------------------------------------------------------------
| PERMISOS
|--------------------------------------------------------------------------
*/

if(
    !isset($_SESSION['can_manage_offices'])
    ||
    intval($_SESSION['can_manage_offices']) !== 1
){
    die("No tienes permisos para acceder a esta sección.");
}

$success = "";
$error = "";

/*
|--------------------------------------------------------------------------
| TABLAS NECESARIAS
|--------------------------------------------------------------------------
*/

$conn->query("
CREATE TABLE IF NOT EXISTS offices (

    id INT AUTO_INCREMENT PRIMARY KEY,

    office_name VARCHAR(255),

    office_city VARCHAR(255),

    status ENUM('active','inactive') DEFAULT 'active',

    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP

)
");

$conn->query("
CREATE TABLE IF NOT EXISTS office_campaigns (

    id INT AUTO_INCREMENT PRIMARY KEY,

    office_id INT NOT NULL,

    campaign_id INT NOT NULL,

    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP

)
");

/*
|--------------------------------------------------------------------------
| VALIDAR COLUMNAS
|--------------------------------------------------------------------------
*/

$checkCity = $conn->query("
SHOW COLUMNS
FROM offices
LIKE 'office_city'
");

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

    $conn->query("
    ALTER TABLE offices
    ADD COLUMN office_city VARCHAR(255) NULL
    ");

}

$checkStatus = $conn->query("
SHOW COLUMNS
FROM offices
LIKE 'status'
");

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

    $conn->query("
    ALTER TABLE offices
    ADD COLUMN status ENUM('active','inactive') DEFAULT 'active'
    ");

}

/*
|--------------------------------------------------------------------------
| CREAR OFICINA
|--------------------------------------------------------------------------
*/

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

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

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

    $campaigns =
    $_POST['campaigns'] ?? [];

    if(
        empty($office_name)
        ||
        empty($office_city)
    ){

        $error =
        "Completa todos los campos.";

    } else {

        $stmt = $conn->prepare("
        INSERT INTO offices
        (
            office_name,
            office_city
        )
        VALUES (?, ?)
        ");

        $stmt->bind_param(
            "ss",
            $office_name,
            $office_city
        );

        if($stmt->execute()){

            $office_id =
            $conn->insert_id;

            foreach($campaigns as $campaign_id){

                $campaign_id =
                intval($campaign_id);

                $conn->query("
                INSERT INTO office_campaigns
                (
                    office_id,
                    campaign_id
                )
                VALUES
                (
                    '$office_id',
                    '$campaign_id'
                )
                ");

            }

            $success =
            "Oficina creada correctamente.";

        }

    }

}

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

if(isset($_GET['toggle'])){

    $office_id =
    intval($_GET['toggle']);

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

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

        $office =
        $officeQuery->fetch_assoc();

        $new_status =
        $office['status'] == 'active'
        ? 'inactive'
        : 'active';

        $conn->query("
        UPDATE offices
        SET status = '$new_status'
        WHERE id = '$office_id'
        ");

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

    }

}

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

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

/*
|--------------------------------------------------------------------------
| OFICINAS
|--------------------------------------------------------------------------
*/

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

?>

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

<head>

<meta charset="UTF-8">

<title>
Oficinas
</title>

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

<style>

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

.back-button{
    display:inline-flex;
    align-items:center;
    gap:8px;
    margin-bottom:20px;
    padding:12px 18px;
    border-radius:14px;
    background:#ffffff;
    color:#02122c;
    text-decoration:none;
    font-size:14px;
    font-weight:700;
    box-shadow:0 6px 18px rgba(15,23,42,.08);
    transition:.2s;
}

.back-button:hover{
    background:#f8fafc;
    transform:translateY(-1px);
}

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

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

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

.form-grid{
    display:grid;
    grid-template-columns:1fr 1fr;
    gap:20px;
}

.form-control{
    height:54px;
    border:none;
    background:#f1f5f9;
    border-radius:14px;
    padding:0 16px;
    font-size:15px;
    width:100%;
}

.multi-select{
    height:240px !important;
    padding:14px !important;
}

.multi-select option{
    padding:12px;
    border-radius:10px;
    margin-bottom:4px;
}

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

.office-card{
    background:#f8fafc;
    padding:24px;
    border-radius:18px;
    margin-bottom:16px;
    display:flex;
    align-items:flex-start;
    justify-content:space-between;
}

.office-left h3{
    margin:0;
    font-size:20px;
    color:#02122c;
}

.office-left p{
    margin-top:8px;
    color:#64748b;
}

.office-campaigns{
    margin-top:15px;
    display:flex;
    flex-wrap:wrap;
    gap:10px;
}

.campaign-badge{
    background:#e0e7ff;
    color:#4338ca;
    padding:8px 12px;
    border-radius:999px;
    font-size:12px;
    font-weight:700;
}

.office-right{
    display:flex;
    align-items:center;
    gap:12px;
}

.badge-active{
    background:#dcfce7;
    color:#166534;
    padding:8px 14px;
    border-radius:999px;
    font-size:12px;
    font-weight:700;
}

.badge-inactive{
    background:#fee2e2;
    color:#991b1b;
    padding:8px 14px;
    border-radius:999px;
    font-size:12px;
    font-weight:700;
}

.btn-action{
    display:inline-flex;
    align-items:center;
    justify-content:center;
    height:40px;
    padding:0 16px;
    border-radius:12px;
    text-decoration:none;
    font-size:13px;
    font-weight:700;
}

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

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

.success-box{
    background:#dcfce7;
    color:#166534;
    padding:15px;
    border-radius:12px;
    margin-bottom:20px;
}

.error-box{
    background:#fee2e2;
    color:#991b1b;
    padding:15px;
    border-radius:12px;
    margin-bottom:20px;
}

.helper-text{
    margin-top:10px;
    font-size:13px;
    color:#64748b;
}

</style>

</head>

<body>

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

<div class="content-area">

    <a
        href="/pages/settings.php"
        class="back-button"
    >
        ← Volver a Settings
    </a>

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

    <div class="page-subtitle">
        Administrar oficinas y campañas
    </div>

    <div class="white-card">

        <?php if($success): ?>

            <div class="success-box">
                <?= $success ?>
            </div>

        <?php endif; ?>

        <?php if($error): ?>

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

        <?php endif; ?>

        <form method="POST">

            <input
                type="hidden"
                name="create_office"
                value="1"
            >

            <div class="form-grid">

                <input
                    type="text"
                    name="office_name"
                    class="form-control"
                    placeholder="Nombre oficina"
                    required
                >

                <input
                    type="text"
                    name="office_city"
                    class="form-control"
                    placeholder="Ciudad"
                    required
                >

            </div>

            <div style="margin-top:20px;">

                <label
                style="
                    display:block;
                    margin-bottom:10px;
                    font-weight:700;
                ">
                    Campañas asignadas
                </label>

                <select
                    name="campaigns[]"
                    class="form-control multi-select"
                    multiple
                >

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

                        <option value="<?= $campaign['id'] ?>">

                            <?= htmlspecialchars($campaign['campaign_name']) ?>

                        </option>

                    <?php endwhile; ?>

                </select>

                <div class="helper-text">
                    Mantén CTRL (Windows) o CMD (Mac) para seleccionar múltiples campañas.
                </div>

            </div>

            <button
                type="submit"
                class="btn-save"
            >
                Crear oficina
            </button>

        </form>

    </div>

    <div class="white-card">

        <?php while($office = $offices->fetch_assoc()): ?>

            <?php

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

            $assigned_campaigns = $conn->query("
            SELECT campaigns.campaign_name
            FROM office_campaigns

            INNER JOIN campaigns
            ON campaigns.id = office_campaigns.campaign_id

            WHERE office_campaigns.office_id = '$office_id'
            ");

            ?>

            <div class="office-card">

                <div class="office-left">

                    <h3>
                        <?= htmlspecialchars($office['office_name']) ?>
                    </h3>

                    <p>
                        <?= htmlspecialchars($office['office_city']) ?>
                    </p>

                    <div class="office-campaigns">

                        <?php
                        while($camp = $assigned_campaigns->fetch_assoc()):
                        ?>

                            <div class="campaign-badge">

                                <?= htmlspecialchars($camp['campaign_name']) ?>

                            </div>

                        <?php endwhile; ?>

                    </div>

                </div>

                <div class="office-right">

                    <?php if($office['status'] == 'active'): ?>

                        <span class="badge-active">
                            Activa
                        </span>

                    <?php else: ?>

                        <span class="badge-inactive">
                            Inactiva
                        </span>

                    <?php endif; ?>

                    <a
                        href="?toggle=<?= $office['id'] ?>"
                        class="btn-action <?= $office['status'] == 'active' ? 'btn-disable' : 'btn-enable' ?>"
                    >

                        <?= $office['status'] == 'active'
                        ? 'Desactivar'
                        : 'Activar'
                        ?>

                    </a>

                </div>

            </div>

        <?php endwhile; ?>

    </div>

</div>

</body>
</html>