<?php
require_once(__DIR__ . '/../ssinclude/app-init.php');
require_once(__DIR__ . '/../ssinclude/app-session.php');

header("Content-Type: application/json");
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Pragma: no-cache");

// ---------------------------------------------------------
// Get & decrypt ID
// ---------------------------------------------------------
$id = verif_get('id');
$global_id = decrypt_data($id);

if (!is_numeric($global_id)) {
    echo json_encode(["status" => "error", "msg" => "ID global invalide"]);
    exit;
}

try {
    // ---------------------------------------------------------
    // 1️⃣ Get global notification
    // ---------------------------------------------------------
    $stmt = $db->prepare("SELECT * FROM global_notifications WHERE id_global = :id");
    $stmt->execute(['id' => $global_id]);
    $global = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$global) {
        echo json_encode(["status" => "error", "msg" => "Notification globale introuvable"]);
        exit;
    }

    // ---------------------------------------------------------
    // 1.1 Prevent repush
    // ---------------------------------------------------------
    if (!empty($global['pushed_on'])) {
        echo json_encode(["status" => "error", "msg" => "Cette notification a déjà été poussée."]);
        exit;
    }

    // ---------------------------------------------------------
    // 2️⃣ Load employees according to schedule group
    // ---------------------------------------------------------
    $group = $global['schedule_group'];

    if ($group === 'ALL') {
        $stmt = $db->query("SELECT employee_id FROM employees WHERE active = 1");
    } else {
        $stmt = $db->prepare("SELECT employee_id FROM employees WHERE active = 1 AND schedule_group = :grp");
        $stmt->execute(['grp' => $group]);
    }

    $employees = $stmt->fetchAll(PDO::FETCH_ASSOC);

    if (empty($employees)) {
        echo json_encode(["status" => "error", "msg" => "Aucun employé actif trouvé dans le groupe sélectionné"]);
        exit;
    }

    // ---------------------------------------------------------
    // 3️⃣ Insert notifications
    // ---------------------------------------------------------
    $insert = $db->prepare("
        INSERT INTO notifications 
        (employee_id, title, message, link, origin_global_id, use_sms, created_on)
        VALUES (:employee_id, :title, :message, :link, :origin_global_id, :use_sms, NOW())
    ");

    foreach ($employees as $emp) {
        $insert->execute([
            'employee_id'      => $emp['employee_id'],
            'title'            => $global['title'],
            'message'          => $global['message'],
            'link'             => $global['link'],
            'use_sms'          => 1,
            'origin_global_id' => $global_id
        ]);
    }

    // ---------------------------------------------------------
    // 4️⃣ Mark as pushed
    // ---------------------------------------------------------
    $update = $db->prepare("UPDATE global_notifications SET pushed_on = NOW() WHERE id_global = :id");
    $update->execute(['id' => $global_id]);

    echo json_encode(["status" => "success"]);

} catch (PDOException $e) {
    echo json_encode(["status" => "error", "msg" => $e->getMessage()]);
}

require_once(__DIR__ . '/../ssinclude/app-close.php');
