<?php 
// On ne démarre la session que si elle n'est pas déjà ouverte
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}
include 'auth.php';

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

if (!isset($_SESSION['admin_token'])) {
    $_SESSION['admin_token'] = bin2hex(random_bytes(32));
}

$file = "./api/language.json";
$jsondata = file_get_contents($file);
$data = json_decode($jsondata, true);

$titles = [];
$contents = [];
$countries = [];
$countryCodes = [];
$contentsto_add_manage = [];

if (is_array($data)) {
    foreach ($data as $index => $item) {
        $words = isset($item["words"]) && is_array($item["words"]) ? $item["words"] : [];

        $titles[$index]               = isset($words["ibo_pro_description"])    ? $words["ibo_pro_description"]    : '';
        $contents[$index]             = isset($words["ibo_pro_general_player"]) ? $words["ibo_pro_general_player"] : '';
        // on protège l'accès à to_add_manage pour éviter le notice
        $contentsto_add_manage[$index]= isset($words["to_add_manage"])          ? $words["to_add_manage"]          : '';

        $countries[$index]    = isset($item["name"]) ? $item["name"] : '';
        $countryCodes[$index] = isset($item["code"]) ? $item["code"] : '';
    }
} else {
    die("Error reading JSON file.");
}

$file1     = "./api/note.json";
$jsondata1 = file_get_contents($file1);
$data1     = json_decode($jsondata1, true);

$selectedCountry = isset($_GET['country']) ? $_GET['country'] : null;
$countryIndex    = $selectedCountry !== null ? array_search($selectedCountry, $countryCodes) : false;

if (isset($_POST["submit"])) {

    if (!isset($_POST['token']) || !hash_equals($_SESSION['admin_token'], $_POST['token'])) {
        header("Location: login.php"); 
        exit(); 
    }

    if ($data !== null && $countryIndex !== false) {
        $replacementData = [
            "ibo_pro_description"    => $_POST["title"],
            "ibo_pro_general_player" => $_POST["content"],
            "to_add_manage"          => $_POST["content_to_add_manage"]
        ];

        $data[$countryIndex]["words"] = array_replace_recursive(
            isset($data[$countryIndex]["words"]) && is_array($data[$countryIndex]["words"])
                ? $data[$countryIndex]["words"]
                : [],
            $replacementData
        );

        $newJsonData = json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
        file_put_contents($file, $newJsonData);
    } else {
        die("Error reading JSON file.");
    }

    if ($data1 !== null) {
        $replacementData1 = [
            "title"                 => $_POST["title"], 
            "content"               => $_POST["content"],
            "content_to_add_manage" => $_POST["content_to_add_manage"]
        ];
        $newData1     = array_replace_recursive($data1, $replacementData1);
        $newJsonData1 = json_encode($newData1, JSON_UNESCAPED_UNICODE);
        file_put_contents($file1, $newJsonData1);
    } else {
        die("Error reading JSON file.");
    }

    header("Location: note.php?r=updated&country=$selectedCountry");
    exit;
}

include 'includes/header.php';
?>

<style>
    .note-header-title {
        font-size: 1.4rem;
        font-weight: 700;
        color: #e5e7eb;
        margin-bottom: 4px;
    }
    .note-header-subtitle {
        font-size: 0.9rem;
        color: #9ca3af;
        margin-bottom: 16px;
    }
    .note-section-title {
        font-size: 0.95rem;
        font-weight: 600;
        color: #e5e7eb;
        margin-bottom: 10px;
    }
    .note-label {
        font-size: 0.8rem;
        font-weight: 600;
        color: #cbd5f5;
        margin-bottom: 4px;
    }
    .input-esso {
        background: rgba(15,23,42,0.95);
        border-radius: 8px;
        border: 1px solid rgba(148,163,184,0.45);
        color: #e5e7eb;
        font-size: 0.88rem;
    }
    .input-esso:focus {
        border-color: #38bdf8;
        box-shadow: 0 0 0 1px rgba(56,189,248,0.5);
        background: rgba(15,23,42,1);
        color: #e5e7eb;
    }
    .btn-esso-primary {
        background: linear-gradient(90deg,#22c55e,#a3e635);
        border: none;
        color: #020617;
        padding: 8px 18px;
        border-radius: 999px;
        font-size: 0.9rem;
        font-weight: 600;
        letter-spacing: .04em;
        text-transform: uppercase;
        cursor: pointer;
    }
    .btn-esso-primary:hover {
        filter: brightness(1.05);
        box-shadow: 0 0 18px rgba(34,197,94,0.35);
    }
    .btn-esso-secondary {
        background: transparent;
        border-radius: 999px;
        border: 1px solid rgba(148,163,184,0.7);
        color: #e5e7eb;
        padding: 7px 16px;
        font-size: 0.85rem;
        font-weight: 500;
        cursor: pointer;
    }
    .btn-esso-secondary:hover {
        background: rgba(15,23,42,0.85);
    }
</style>

<div class="container-fluid page-shell-esso">
    <div class="panel-card-esso">
        <div class="note-header">
            <h1 class="note-header-title">Panel Messages</h1>
            <div class="note-header-subtitle">
                Configure the messages shown in the app for each language / country.
            </div>
        </div>

        <?php if (isset($_GET['r'])): ?>
            <?php $result = $_GET['r']; ?>
            <?php switch ($result):
                case "updated": ?>
                    <script>
                        const Toast = Swal.mixin({
                            toast: true,
                            position: 'bottom',
                            showConfirmButton: false,
                            timer: 2000,
                        });
                        Toast.fire({
                            icon: 'success',
                            title: 'Message updated successfully!'
                        });
                    </script>
                    <?php break; ?>
            <?php endswitch; ?>
        <?php endif; ?>

        <div class="card-body p-0 mt-2">
            <?php if ($selectedCountry === null || $countryIndex === false): ?>
                <div class="note-section-title">
                    <i class="fa fa-globe-americas mr-1"></i> Select Country
                </div>
                <form method="get" class="mt-2">
                    <div class="form-group">
                        <label for="country" class="note-label">Choose a country / language</label>
                        <select class="form-control input-esso" name="country" id="country" required>
                            <?php foreach ($countries as $index => $country): ?>
                                <option value="<?php echo htmlspecialchars($countryCodes[$index], ENT_QUOTES); ?>">
                                    <?php echo htmlspecialchars($country, ENT_QUOTES); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <button type="submit" class="btn-esso-primary mt-1">Continue</button>
                </form>
            <?php else: ?>
                <div class="note-section-title">
                    <i class="fa fa-bullhorn mr-1"></i>
                    Edit Messages for <?php echo htmlspecialchars($countries[$countryIndex], ENT_QUOTES); ?>
                </div>
                <form method="post" class="mt-3">
                    <input type="hidden" name="token" value="<?= $_SESSION['admin_token']; ?>">
                    
                    <div class="form-group">
                        <label for="title" class="note-label">Title</label>
                        <div class="input-group">
                            <input
                                type="text"
                                class="form-control input-esso"
                                id="title"
                                name="title"
                                placeholder="TITLE"
                                value="<?php echo htmlspecialchars($titles[$countryIndex], ENT_QUOTES); ?>">
                        </div>
                    </div>

                    <div class="form-group">
                        <label for="content" class="note-label">Message</label>
                        <div class="input-group">
                            <input
                                type="text"
                                class="form-control input-esso"
                                id="content"
                                name="content"
                                placeholder="MESSAGE"
                                value="<?php echo htmlspecialchars($contents[$countryIndex], ENT_QUOTES); ?>">
                        </div>
                    </div>

                    <div class="form-group">
                        <label for="content_to_add_manage" class="note-label">Secondary Message</label>
                        <div class="input-group">
                            <input
                                type="text"
                                class="form-control input-esso"
                                id="content_to_add_manage"
                                name="content_to_add_manage"
                                placeholder="MESSAGE 2"
                                value="<?php echo htmlspecialchars($contentsto_add_manage[$countryIndex], ENT_QUOTES); ?>">
                        </div>
                    </div>

                    <button type="submit" name="submit" class="btn-esso-primary mt-1">
                        Save
                    </button>
                    <a href="note.php" class="btn-esso-secondary mt-1 ml-2">
                        Back to country selection
                    </a>
                </form>
            <?php endif; ?>
        </div>
    </div>
</div>

<?php include 'includes/footer.php'; ?>
