<?php

/**

 * Weekly Feeding Fee Summary Script

 * Sends SMS to parents on Friday evening with the amount paid for the week

 *

 * CRON SETUP (run every Friday at 6 PM):

 * 0 18 * * 5 php /path/to/your/site/send_weekly_feeding_summary.php

 *

 * Or via web with token:

 * GET /send_weekly_feeding_summary.php?token=YOUR_CRON_TOKEN

 */



// ── Cron guard: only allow CLI or authenticated web requests ───────────

$_is_cli   = php_sapi_name() === 'cli';

$_is_web   = !$_is_cli;

$_token    = $_GET['token'] ?? ($_SERVER['HTTP_X_CRON_TOKEN'] ?? '');

// Token is read from config after require; default fallback for early check

if ($_is_web) {

    // Temporarily load token from settings after config is available

    define('CRON_GUARD_PENDING', true);

}



require_once 'config.php';



// Web guard: validate token against DB setting

if (defined('CRON_GUARD_PENDING') && $_is_web) {

    $conn_guard = getDBConnection();

    $cron_token = '';

    if ($conn_guard instanceof mysqli) {

        $r = $conn_guard->query("SELECT setting_value FROM settings WHERE setting_key='cron_token' LIMIT 1");

        if ($r && $row = $r->fetch_assoc()) $cron_token = $row['setting_value'];

    }

    if ($cron_token === '' || $_token !== $cron_token) {

        http_response_code(403);

        exit('Forbidden — invalid or missing cron token.');

    }

}



// Disable time limit

set_time_limit(300);



// Get database connection

$conn = getDBConnection();



if (!$conn) {

    die("Database connection failed");

}



// Calculate current week (Monday to Friday)

$today = new DateTime();

$week_start = clone $today;

$week_start->modify('monday this week');

$week_end = clone $week_start;

$week_end->modify('friday this week');



$week_start_str = $week_start->format('Y-m-d');

$week_end_str = $week_end->format('Y-m-d');

$week_display = $week_start->format('d M') . ' - ' . $week_end->format('d M Y');



echo "Processing feeding fee summaries for week: $week_display\n";



// Get all active students with their feeding fee payments for this week

$query = "SELECT 

    s.id,

    s.student_id,

    s.first_name,

    s.last_name,

    s.father_name AS parent_name,

    s.father_phone AS phone,

    COALESCE(wfp.amount_paid, 0) as amount_paid,

    wfp.id as week_payment_id,

    wfp.sms_sent

FROM students s

LEFT JOIN weekly_feeding_payments wfp ON s.id = wfp.student_id 

    AND wfp.week_start_date = ?

WHERE s.status = 'active'

ORDER BY s.class, s.first_name";



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

$stmt->bind_param("s", $week_start_str);

$stmt->execute();

$result = $stmt->get_result();



$students = [];

while ($row = $result->fetch_assoc()) {

    $students[] = $row;

}

$stmt->close();



echo "Found " . count($students) . " active students\n";



$school_name = getSetting('school_name', 'Our School');

$success_count = 0;

$fail_count = 0;

$no_phone_count = 0;



foreach ($students as $student) {

    // Skip if already sent SMS for this week

    if ($student['sms_sent']) {

        echo "SMS already sent for {$student['first_name']} {$student['last_name']}\n";

        continue;

    }

    

    $student_name = $student['first_name'] . ' ' . $student['last_name'];

    $parent_name = $student['parent_name'] ?: 'Parent';

    $phone = $student['phone'] ?? '';

    $amount_paid = $student['amount_paid'];

    

    if (empty($phone)) {

        echo "No phone number for {$student_name}\n";

        $no_phone_count++;

        continue;

    }

    

    $formatted_amount = formatCurrency($amount_paid);

    

    // Create appropriate message based on whether payment was made

    if ($amount_paid > 0) {

        $sms_message = "Dear {$parent_name}, This week ({$week_display}), you have paid {$formatted_amount} for {$student_name}'s feeding fee. Thank you for your timely payment. - {$school_name}";

    } else {

        $sms_message = "Dear {$parent_name}, No feeding fee payment was recorded for {$student_name} this week ({$week_display}). Please ensure payment is made by Monday to avoid disruption. - {$school_name}";

    }

    

    // Send SMS

    $sms_sent = sendSMS($phone, $sms_message);

    

    if ($sms_sent) {

        $success_count++;

        echo "✓ Summary sent to {$parent_name} for {$student_name}\n";

        

        // Update the weekly record if it exists

        if ($student['week_payment_id']) {

            $update = "UPDATE weekly_feeding_payments SET sms_sent = TRUE, sms_sent_date = NOW() WHERE id = ?";

            $update_stmt = $conn->prepare($update);

            $update_stmt->bind_param("i", $student['week_payment_id']);

            $update_stmt->execute();

            $update_stmt->close();

        }

    } else {

        $fail_count++;

        echo "✗ Failed to send summary to {$parent_name} for {$student_name}\n";

    }

    

    // Small delay to prevent API rate limiting

    usleep(300000); // 0.3 second delay

}



echo "\nWeekly feeding fee summary completed:\n";

echo "Total students: " . count($students) . "\n";

echo "SMS sent: $success_count\n";

echo "Failed: $fail_count\n";

echo "No phone: $no_phone_count\n";



// Log activity

logActivity($conn, 1, 'Weekly Feeding Summary', 

            "Sent weekly feeding fee summaries to $success_count parents");



$conn->close();

?>