<?php

require_once __DIR__ . '/user-ssinclude/user-init.php';
require_once __DIR__ . '/adminfs/ssinclude/classes/class.sms.php';
require_once __DIR__ . '/adminfs/ssinclude/classes/class.mailer.php';

$smsClient = new SMSClient();

// -----------------------------------------------------------------------------
// 1. Fetch notifications in batches of 10
// -----------------------------------------------------------------------------
$sql = "
    SELECT 
        n.id_notification,
        n.employee_id,
        n.title,
        n.message,
        n.use_sms,
        n.use_email,
        n.sms_sent,
        n.email_sent,
        e.first_name,
        e.last_name,
        e.phone_number,
        e.email
    FROM notifications n
    INNER JOIN employees e ON e.employee_id = n.employee_id
    WHERE (n.sms_sent = 0 OR n.email_sent = 0)
    ORDER BY n.id_notification ASC
    LIMIT 10
";

$statement = $db->prepare($sql);
$statement->execute();
$notifications = $statement->fetchAll(PDO::FETCH_ASSOC);

if (!$notifications) {
    exit;
}

// -----------------------------------------------------------------------------
// 2. Process notifications
// -----------------------------------------------------------------------------
foreach ($notifications as $row) {

    $notifId = $row['id_notification'];
    $empId   = $row['employee_id'];
    $empName = $row['first_name'] . " " . $row['last_name'];
    $message = $row['message'];

    // -------------------------------------------------------------------------
    // FORMAT PHONE NUMBER (prepend 216 only) Tunisia 
    // -------------------------------------------------------------------------
    $phone = trim($row['phone_number']);

    if (!empty($phone)) {

        // Extract digits only
        $digits = preg_replace('/[^0-9]/', '', $phone);

        // If it does NOT start with 216, add it
        if (strpos($digits, '216') !== 0) {
            $phone = '216' . $digits;
        } else {
            $phone = $digits;
        }
    }

    // -------------------------
    // SEND SMS
    // -------------------------
    if ($row['use_sms'] == 1 && $row['sms_sent'] == 0) {

        if (!empty($phone)) {

            $smsResult = $smsClient->sendSMS($phone, $message);

            // Log raw API response
            logAction("[EMP #$empId | $empName | Notif #$notifId] SMS RAW → " . json_encode($smsResult));

            if (!empty($smsResult['success'])) {

                $db->prepare("UPDATE notifications SET sms_sent = 1 WHERE id_notification = ?")
                   ->execute([$notifId]);

                logAction("[EMP #$empId | $empName | Notif #$notifId] SMS SENT to $phone");

            } else {
                logAction("[EMP #$empId | $empName | Notif #$notifId] SMS ERROR → " . ($smsResult['error'] ?? 'Unknown error'));
            }

        } else {
            logAction("[EMP #$empId | $empName | Notif #$notifId] SMS SKIPPED: no phone number");
        }
    }

    // -------------------------
    // SEND EMAIL
    // -------------------------
    if ($row['use_email'] == 1 && $row['email_sent'] == 0) {

        if (!empty($row['email']) && filter_var($row['email'], FILTER_VALIDATE_EMAIL)) {

            $emailResult = sendAppEmail($row['email'], $row['title'], $message);

            // Log raw mailer response
            logAction("[EMP #$empId | $empName | Notif #$notifId] EMAIL RAW → " . json_encode($emailResult));

            if (!empty($emailResult['success'])) {

                $db->prepare("UPDATE notifications SET email_sent = 1 WHERE id_notification = ?")
                   ->execute([$notifId]);

                logAction("[EMP #$empId | $empName | Notif #$notifId] EMAIL SENT to {$row['email']}");

            } else {
                logAction("[EMP #$empId | $empName | Notif #$notifId] EMAIL ERROR → " . ($emailResult['error'] ?? 'Unknown error'));
            }

        } else {
            logAction("[EMP #$empId | $empName | Notif #$notifId] EMAIL SKIPPED: invalid email");
        }
    }
}

// -----------------------------------------------------------------------------
// LOGGING FUNCTION
// -----------------------------------------------------------------------------
function logAction($text)
{
    global $db;
    $stmt = $db->prepare("INSERT INTO logs (log) VALUES (?)");
    $stmt->execute([$text]);
}

echo "DONE\n";
