<?php
/**
 * Action: Cancel a canteen session and SMS parents of pending entitlements.
 */

if (!defined('DB_HOST')) {
    require_once __DIR__ . '/../../config.php';
}
require_once __DIR__ . '/../../includes/canteen_helpers.php';

function action_cancel_canteen_session(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;
    $session_name = trim((string) ($params['session_name'] ?? ''));
    $date         = trim((string) ($params['date'] ?? date('Y-m-d')));

    // Resolve session_id from name+date if not provided
    if ($session_id <= 0 && $session_name !== '') {
        $find = $conn->prepare(
            "SELECT id FROM canteen_sessions
             WHERE school_id = 1 AND session_date = ?
               AND session_name LIKE ? AND status != 'cancelled'
             LIMIT 1"
        );
        $like = '%' . $session_name . '%';
        $find->bind_param('ss', $date, $like);
        $find->execute();
        $row = $find->get_result()->fetch_assoc();
        $find->close();
        if ($row) $session_id = (int) $row['id'];
    }

    if ($session_id <= 0) {
        return ['success' => false, 'error' => 'Session not found. Provide session_id or session_name + date.'];
    }

    // Load session info
    $info_stmt = $conn->prepare(
        "SELECT session_name, session_date, status FROM canteen_sessions WHERE id = ? AND school_id = 1"
    );
    $info_stmt->bind_param('i', $session_id);
    $info_stmt->execute();
    $session = $info_stmt->get_result()->fetch_assoc();
    $info_stmt->close();

    if (!$session) {
        return ['success' => false, 'error' => 'Session not found.'];
    }
    if ($session['status'] === 'cancelled') {
        return ['success' => false, 'error' => "Session '{$session['session_name']}' is already cancelled."];
    }

    // Cancel session
    $upd = $conn->prepare("UPDATE canteen_sessions SET status = 'cancelled' WHERE id = ?");
    $upd->bind_param('i', $session_id);
    $upd->execute();
    $upd->close();

    // Cancel pending entitlements
    $ce_upd = $conn->prepare(
        "UPDATE canteen_entitlements SET status = 'cancelled'
         WHERE session_id = ? AND status = 'pending'"
    );
    $ce_upd->bind_param('i', $session_id);
    $ce_upd->execute();
    $cancelled_entitlements = $conn->affected_rows;
    $ce_upd->close();

    // SMS parents of pending students
    $school_name = getSettingValue('school_name') ?: 'the school';
    $sms_sent    = 0;

    $par_stmt = $conn->prepare(
        "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
         FROM canteen_entitlements ce
         JOIN students s ON s.id = ce.student_id
         WHERE ce.session_id = ? AND ce.status = 'cancelled'
           AND (s.father_phone IS NOT NULL OR s.mother_phone IS NOT NULL)"
    );
    $par_stmt->bind_param('i', $session_id);
    $par_stmt->execute();
    $parents = $par_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $par_stmt->close();
    $conn->close();

    $sess_label = $session['session_name'] . ' on ' . date('d M Y', strtotime($session['session_date']));
    foreach ($parents as $p) {
        if (empty($p['phone'])) continue;
        $msg = "Dear {$p['parent_name']}, the {$sess_label} canteen session at {$school_name} has been cancelled. No canteen pass is required today. — {$school_name}";
        if (function_exists('sendSMS') && sendSMS($p['phone'], $msg)) {
            $sms_sent++;
        }
    }

    return [
        'success'                 => true,
        'session_id'              => $session_id,
        'session_name'            => $session['session_name'],
        'session_date'            => $session['session_date'],
        'cancelled_entitlements'  => $cancelled_entitlements,
        'sms_sent'                => $sms_sent,
        'message'                 => "Session '{$session['session_name']}' cancelled. {$cancelled_entitlements} entitlement(s) cancelled. {$sms_sent} parent(s) notified by SMS.",
    ];
}
