<?php

/**

 * Action: Send SMS reminder to parents of students with pending (unconfirmed) canteen entitlements.

 */



if (!defined('DB_HOST')) {

    require_once __DIR__ . '/../../config.php';

}

require_once __DIR__ . '/../../includes/canteen_helpers.php';



function action_send_canteen_reminder_sms(array $params): array

{

    if (!canteen_is_active()) {

        return ['success' => false, 'error' => 'Canteen module is not active.'];

    }



    $conn       = getDBConnection();

    $session_id = isset($params['session_id']) ? (int) $params['session_id'] : 0;

    $class_name = trim((string) ($params['class_name'] ?? ''));

    $today      = date('Y-m-d');



    // If no session_id, use today's active/scheduled sessions

    if ($session_id <= 0) {

        $sess_stmt = $conn->prepare(

            "SELECT id, session_name FROM canteen_sessions

             WHERE school_id = 1 AND session_date = ? AND status IN ('scheduled','active')

             ORDER BY start_time ASC"

        );

        $sess_stmt->bind_param('s', $today);

        $sess_stmt->execute();

        $sessions = $sess_stmt->get_result()->fetch_all(MYSQLI_ASSOC);

        $sess_stmt->close();

    } else {

        $sess_stmt = $conn->prepare(

            "SELECT id, session_name FROM canteen_sessions WHERE id = ? AND school_id = 1"

        );

        $sess_stmt->bind_param('i', $session_id);

        $sess_stmt->execute();

        $sessions = $sess_stmt->get_result()->fetch_all(MYSQLI_ASSOC);

        $sess_stmt->close();

    }



    if (empty($sessions)) {

        return ['success' => false, 'error' => 'No active canteen sessions found for today.'];

    }



    $session_ids  = array_column($sessions, 'id');

    $session_name = implode(', ', array_column($sessions, 'session_name'));

    $school_name  = getSettingValue('school_name') ?: 'the school';



    // Build query for pending entitlements

    $id_placeholders = implode(',', array_fill(0, count($session_ids), '?'));

    $types = str_repeat('i', count($session_ids));



    $sql = "SELECT DISTINCT s.first_name, s.last_name,

                   COALESCE(s.father_phone, s.mother_phone) AS phone,

                   COALESCE(s.father_name, s.mother_name, 'Parent') AS parent_name,

                   cs.session_name

            FROM canteen_entitlements ce

            JOIN students s  ON s.id  = ce.student_id

            JOIN canteen_sessions cs ON cs.id = ce.session_id

            WHERE ce.session_id IN ({$id_placeholders})

              AND ce.status = 'pending'

              AND (s.father_phone IS NOT NULL OR s.mother_phone IS NOT NULL)";



    if ($class_name !== '') {

        $sql   .= " AND s.class = ?";

        $types .= 's';

        $session_ids[] = $class_name;

    }



    $stmt = $conn->prepare($sql);

    $stmt->bind_param($types, ...$session_ids);

    $stmt->execute();

    $pending = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);

    $stmt->close();

    $conn->close();



    if (empty($pending)) {

        return [

            'success' => true,

            'sms_sent'=> 0,

            'message' => 'No pending entitlements found' . ($class_name ? " for {$class_name}" : '') . '. No reminders sent.',

        ];

    }



    $sms_sent = 0;

    $failed   = 0;

    foreach ($pending as $p) {

        if (empty($p['phone'])) continue;

        $student_name = trim($p['first_name'] . ' ' . $p['last_name']);

        $msg = "[{$school_name}] Dear {$p['parent_name']},\n{$student_name}'s canteen pass for {$p['session_name']} today has not yet been used. Please remind your child to present their pass at the canteen window before the session ends.\nThank you.";

        if (strlen($msg) > 320) $msg = substr($msg, 0, 317) . '...';

        if (function_exists('sendSMS') && sendSMS($p['phone'], $msg)) {

            $sms_sent++;

        } else {

            $failed++;

        }

    }



    $scope = $class_name ? " for {$class_name}" : '';

    return [

        'success'  => true,

        'sessions' => $session_name,

        'pending'  => count($pending),

        'sms_sent' => $sms_sent,

        'failed'   => $failed,

        'message'  => "Sent {$sms_sent} reminder SMS{$scope} for {$session_name}. {$failed} failed.",

    ];

}

