<?php

session_start();

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

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

requirePermission('can_manage_campaigns');

$success = '';
$error = '';

/*
============================================
GUARDAR
============================================
*/

if($_SERVER['REQUEST_METHOD'] === 'POST'){

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

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

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

    if(
        $campaign_id > 0
        &&
        $whatsapp_number != ''
    ){

        /*
        ============================================
        EXISTE?
        ============================================
        */

        $check = $conn->prepare("
            SELECT id
            FROM whatsapp_campaigns
            WHERE campaign_id = ?
        ");

        $check->bind_param(
            "i",
            $campaign_id
        );

        $check->execute();

        $result =
        $check->get_result();

        /*
        ============================================
        UPDATE
        ============================================
        */

        if($result->num_rows > 0){

            $update = $conn->prepare("
                UPDATE whatsapp_campaigns
                SET
                    whatsapp_number = ?,
                    whatsapp_name = ?
                WHERE campaign_id = ?
            ");

            $update->bind_param(
                "ssi",
                $whatsapp_number,
                $whatsapp_name,
                $campaign_id
            );

            $update->execute();

        } else {

            /*
            ============================================
            INSERT
            ============================================
            */

            $insert = $conn->prepare("
                INSERT INTO whatsapp_campaigns
                (
                    campaign_id,
                    whatsapp_number,
                    whatsapp_name
                )
                VALUES
                (
                    ?, ?, ?
                )
            ");

            $insert->bind_param(
                "iss",
                $campaign_id,
                $whatsapp_number,
                $whatsapp_name
            );

            $insert->execute();
        }

        $success =
        "WhatsApp guardado correctamente.";

    } else {

        $error =
        "Debes completar todos los campos.";
    }
}

/*
============================================
LISTAR
============================================
*/

$list = $conn->query("

SELECT
    campaigns.id,
    campaigns.campaign_name,
    whatsapp_campaigns.whatsapp_number,
    whatsapp_campaigns.whatsapp_name

FROM campaigns

LEFT JOIN whatsapp_campaigns
ON whatsapp_campaigns.campaign_id = campaigns.id

ORDER BY campaigns.campaign_name ASC

");

?>

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

<head>

<meta charset="UTF-8">

<title>
Settings WhatsApp
</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;
    margin-bottom:10px;
    color:#02122c;
}

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

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

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

.form-group{
    display:flex;
    flex-direction:column;
}

.form-group label{
    margin-bottom:10px;
    font-size:14px;
    font-weight:700;
}

.form-control{
    height:52px;
    border:none;
    background:#f3f5fa;
    border-radius:14px;
    padding:0 16px;
}

.btn-save{
    margin-top:25px;
    background:#5b3df5;
    color:#fff;
    border:none;
    height:52px;
    padding:0 24px;
    border-radius:14px;
    font-weight:700;
    cursor:pointer;
}

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

.crm-table th{
    text-align:left;
    padding:16px;
    border-bottom:1px solid #edf0f5;
}

.crm-table td{
    padding:16px;
    border-bottom:1px solid #edf0f5;
}

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

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

</style>

</head>

<body>

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

<div class="content-area">

    <div class="page-title">
        WhatsApp Campañas
    </div>

    <div class="page-subtitle">
        Configuración centralizada de WhatsApp
    </div>

    <?php if($success): ?>

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

    <?php endif; ?>

    <?php if($error): ?>

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

    <?php endif; ?>

    <div class="white-card">

        <form method="POST">

            <div class="form-grid">

                <div class="form-group">

                    <label>
                        Campaña
                    </label>

                    <select
                        name="campaign_id"
                        class="form-control"
                        required
                    >

                        <option value="">
                            Seleccionar
                        </option>

                        <?php

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

                        while($c = $campaigns->fetch_assoc()):

                        ?>

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

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

                        </option>

                        <?php endwhile; ?>

                    </select>

                </div>

                <div class="form-group">

                    <label>
                        Número WhatsApp
                    </label>

                    <input
                        type="text"
                        name="whatsapp_number"
                        class="form-control"
                        placeholder="573001112233"
                        required
                    >

                </div>

                <div class="form-group">

                    <label>
                        Nombre Comercial
                    </label>

                    <input
                        type="text"
                        name="whatsapp_name"
                        class="form-control"
                        placeholder="Wolfxell Energía"
                    >

                </div>

            </div>

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

        </form>

    </div>

    <div class="white-card">

        <table class="crm-table">

            <thead>

                <tr>

                    <th>Campaña</th>
                    <th>WhatsApp</th>
                    <th>Nombre</th>

                </tr>

            </thead>

            <tbody>

                <?php while($row = $list->fetch_assoc()): ?>

                <tr>

                    <td>
                        <?= htmlspecialchars($row['campaign_name']) ?>
                    </td>

                    <td>
                        <?= htmlspecialchars($row['whatsapp_number']) ?>
                    </td>

                    <td>
                        <?= htmlspecialchars($row['whatsapp_name']) ?>
                    </td>

                </tr>

                <?php endwhile; ?>

            </tbody>

        </table>

    </div>

</div>

</body>
</html>