<?php
/**
 * Action: Deliver terminal report cards to parents over WhatsApp (PDF documents).
 * Renders each student's report to a publicly-served PDF and sends it as a
 * WhatsApp document to the parent's number.
 *
 * NOTE: WhatsApp fetches the document by URL, so BASE_URL must be a public https
 * address for delivery to succeed (localhost will render PDFs but Meta cannot
 * fetch them). The action still reports exactly what happened per student.
 */

if (!defined('DB_HOST')) {
    require_once __DIR__ . '/../../config.php';
}
require_once __DIR__ . '/../../includes/whatsapp_lib.php';
require_once __DIR__ . '/../../modules/reports/lib/report_pdf_render.php';
require_once __DIR__ . '/batch_generate_report_pdfs.php';   // rbcReportPdfBaseUrl(), rbcPruneOldReportZips()

function action_deliver_reports_whatsapp(array $params): array
{
    if (!function_exists('hasModule') || !hasModule('whatsapp_comms')) {
        return ['success' => false, 'error' => 'The WhatsApp add-on is not active for this school.'];
    }
    if (!wa_is_configured()) {
        return ['success' => false, 'error' => 'WhatsApp is not configured. Set it up on the WhatsApp page first.'];
    }

    $conn          = getDBConnection();
    $class_name    = trim((string) ($params['class_name'] ?? ''));
    $term          = (string) ($params['term'] ?? getSettingValue('current_term') ?? 'First Term');
    $academic_year = (string) ($params['academic_year'] ?? getSettingValue('academic_year') ?? date('Y'));
    $school_name   = getSettingValue('school_name') ?: 'the school';

    if ($class_name === '') return ['success' => false, 'error' => 'class_name is required.'];

    $stmt = $conn->prepare(
        "SELECT DISTINCT s.id, s.first_name, s.last_name, s.father_phone, s.mother_phone, s.phone
         FROM students s
         JOIN report_details rd ON rd.student_id = s.id
         WHERE s.class=? AND rd.term=? AND rd.academic_year=? AND s.status='active'
         ORDER BY s.first_name, s.last_name"
    );
    $stmt->bind_param('sss', $class_name, $term, $academic_year);
    $stmt->execute();
    $students = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $stmt->close();

    if (empty($students)) {
        return ['success' => false, 'error' => "No report details found for {$class_name} {$term} ({$academic_year})."];
    }

    $root = __DIR__ . '/../../uploads/report_pdfs';
    if (function_exists('rbcPruneOldReportZips')) rbcPruneOldReportZips($root);
    $safe_term = trim((string) preg_replace('/[^A-Za-z0-9_\-]/', '_', $term), '_');
    $token     = bin2hex(random_bytes(8));
    $dir       = $root . "/wa_{$safe_term}_{$token}";
    if (!is_dir($dir) && !@mkdir($dir, 0755, true) && !is_dir($dir)) {
        return ['success' => false, 'error' => 'Could not create the output directory.'];
    }

    $sent = 0; $failed = 0; $no_phone = 0; $render_fail = 0;
    foreach ($students as $stu) {
        $phone = trim((string) ($stu['father_phone'] ?: $stu['mother_phone'] ?: $stu['phone'] ?: ''));
        if ($phone === '') { $no_phone++; continue; }

        try {
            $bytes = renderReportPdfBytes($conn, (int) $stu['id'], $term, $academic_year);
            if (strlen($bytes) < 100) throw new RuntimeException('empty render');
            $filename = reportPdfFilename($stu, $safe_term);
            $abs = $dir . '/' . $filename;
            if (@file_put_contents($abs, $bytes) === false) throw new RuntimeException('write failed');
        } catch (Throwable $e) {
            $render_fail++;
            continue;
        }

        $rel     = "uploads/report_pdfs/wa_{$safe_term}_{$token}/" . rawurlencode(basename($abs));
        $url     = rbcReportPdfBaseUrl() . $rel;
        $name    = trim(($stu['first_name'] ?? '') . ' ' . ($stu['last_name'] ?? ''));
        $caption = "Terminal report for {$name} — {$term}, {$academic_year}. — {$school_name}";
        $res = send_whatsapp_document($phone, $url, basename($abs), $caption);
        if (!empty($res['success'])) $sent++; else $failed++;
    }

    return [
        'success'      => true,
        'message'      => "Report delivery — {$sent} sent, {$failed} failed, {$render_fail} could not render, {$no_phone} without a number.",
        'sent'         => $sent, 'failed' => $failed,
        'render_failed'=> $render_fail, 'no_phone' => $no_phone,
        'class_name'   => $class_name, 'term' => $term, 'academic_year' => $academic_year,
    ];
}
