<?php
/**
 * Message to Students API
 * 
 * Handles fetching students and sending messages via Email and WhatsApp.
 */
ini_set('display_errors', 0);
error_reporting(E_ALL);

header('Content-Type: application/json');

// Addressing PHPSESSID SameSite rejection
session_start();

require_once('../libs/classes/DbPathsArray.php');
require_once('../libs/classes/App_DB.php');
require_once('../libs/classes/MyMethods.php');
require_once('../libs/classes/Mailer.php');
require_once('../libs/classes/WhatsApp.php');

if (!isset($_SESSION['userid'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

$crud = new App_DB(DBU::$dba_user);
$action = $_REQUEST['action'] ?? '';

$response = ['success' => false, 'message' => 'Invalid action'];

switch ($action) {
    case 'fetchStudents':
        $darja = $_GET['darja'] ?? '';
        if (empty($darja)) {
            $response['message'] = 'Darja is required';
            break;
        }

        // Fetch active students (isActive = 1) from registrationinfo joined with stddarjaat
        $sql = "SELECT r.sno, r.stdName, r.fatherName, r.cellNo, r.contact_email AS email 
                FROM registrationinfo r
                JOIN stddarjaat s ON r.sno = s.stdSno
                WHERE s.darja = :darja AND r.isActive = 1
                ORDER BY r.stdName ASC";

        $students = $crud->getRecordSet($sql, ['darja' => $darja]);
        $response = ['success' => true, 'students' => $students];
        break;

    case 'sendMessages':
        $studentsJson = $_POST['students'] ?? '';
        $message = $_POST['message'] ?? '';
        $sendEmail = $_POST['send_email'] === 'true';
        $sendWhatsapp = $_POST['send_whatsapp'] === 'true';

        if (empty($studentsJson) || empty($message)) {
            $response['message'] = 'Missing data (students or message)';
            break;
        }

        $students = json_decode($studentsJson, true);
        if (!$students) {
            $response['message'] = 'Invalid student data';
            break;
        }

        $mailer = new Communicator();
        $whatsapp = new WhatsApp();

        $successCount = 0;
        $failureCount = 0;
        $logDetails = [];

        // Prepare Plain Text for WhatsApp
        $plainMessage = strip_tags(str_replace(['<br>', '<br />', '</div>', '</p>'], "\n", $message));
        $plainMessage = html_entity_decode($plainMessage);

        foreach ($students as $std) {
            $emailSent = true;
            $whatsappSent = true;
            $errors = [];

            // 1. Send Email
            if ($sendEmail) {
                if (!empty($std['email'])) {
                    $emailSent = $mailer->sendEmailRnd([$std['email']], "", "پیغام از مدرسہ", $message);
                    if (!$emailSent) {
                        $errors[] = "Email Failed: " . $mailer->tempVar;
                    }
                } else {
                    $emailSent = false;
                    $errors[] = "Email Missing";
                }
            }

            // 2. Send WhatsApp
            if ($sendWhatsapp) {
                if (!empty($std['phone'])) {
                    $res = $whatsapp->sendMessage($std['phone'], $plainMessage);
                    $whatsappSent = $res['success'];
                    if (!$whatsappSent) {
                        $errors[] = "WhatsApp Failed: " . $res['message'];
                    }
                } else {
                    $whatsappSent = false;
                    $errors[] = "Phone Missing";
                }
            }

            if ($emailSent && $whatsappSent) {
                $successCount++;
                $logDetails[] = "SUCCESS: [{$std['sno']}] {$std['stdName']} - Sent to " .
                    ($sendEmail ? $std['email'] : '') . " " .
                    ($sendWhatsapp ? $std['phone'] : '');
            } else {
                $failureCount++;
                $logDetails[] = "FAILURE: [{$std['sno']}] {$std['stdName']} - Errors: " . implode(', ', $errors);
            }
        }

        // Logging
        $timestamp = date('Y-m-d_H-i-s');
        $logFileName = "{$timestamp}_log.txt";
        $logFilePath = "../logs/messages_logs/{$logFileName}";

        $logContent = "Message Sending Log - {$timestamp}\n";
        $logContent .= "Total Students: " . count($students) . "\n";
        $logContent .= "Success: {$successCount}\n";
        $logContent .= "Failure: {$failureCount}\n";
        $logContent .= "Message Body: \n---\n{$plainMessage}\n---\n\n";
        $logContent .= "Details:\n" . implode("\n", $logDetails);

        file_put_contents($logFilePath, $logContent);

        $response = [
            'success' => true,
            'results' => [
                'success' => $successCount,
                'failure' => $failureCount
            ],
            'logFile' => $logFileName
        ];
        break;
}

echo json_encode($response);
