<?php
include "../include/config.php";

if (isset($_POST['sms'])) {
    $term = $_POST['term'];
    $year = $_POST['year'];
    $intake = $_POST['intake'];
    $program = $_POST['program'];
    $balance = $_POST['balance'];
    $school = strtoupper($_POST['school']);
}

if ($balance === null || $balance == 0) {
    header("location:smsac?smsf=Insufficient balance please Top up!");
    exit();
}

$apiKey = "76d2ea13-10e0-48e7-8e0e-7261bac5ced7"; 
$apiSecret = "0b15eb80a64d3528cbfc6cd76889b7e71af204aa"; 
$senderId = "ZAMATECHNOL";

function getAuthToken($apiKey, $apiSecret) {
    $url = "https://tumeny.herokuapp.com/api/token";
    $headers = [
        "apiKey: $apiKey",
        "apiSecret: $apiSecret",
        "Content-Type: application/json"
    ];

    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($httpCode == 200) {
        $responseArray = json_decode($response, true);
        return $responseArray['token'];
    } else {
        echo "Failed to generate token. HTTP Code: $httpCode. Response: $response";
        return null;
    }
}

function sendSms($authToken, $senderId, $message, $recipients) {
    $url = "https://tumeny.herokuapp.com/api/v1/sms/send";
    $headers = [
        "Authorization: Bearer $authToken",
        "Content-Type: application/json"
    ];

    $payload = json_encode([
        "sender" => $senderId,
        "message" => $message,
        "recipient" => $recipients
    ]);

    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);

    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    return $httpCode == 200 ? json_decode($response, true) : ["status" => "error", "message" => $response];
}

$subjectAbbreviations = [
    "history" => "His",
    "Home economics" => "HE",
    "English" => "Eng",
    "Integrated science" => "IntSci",
    "Mathematics" => "MATH",
    "Biology" => "Bio",
    "Science 5124" => "Scie",
    "Agriculture science" => "AGRIC",
    "Physics" => "Phys",
    "Chemistry" => "Che",
    "Religious education" => "RE",
    "Home Management" => "HM",
    "Geography" => "Geo",
    "Business Studies" => "BS",
    "Principles of Accounts" => "PA",
    "Computer Studies" => "COM",
    "Social studies" => "SS",
    "Additional Maths" => "ADDIMA",
    "Commerce" => "COMM",
    "Computer Science" => "CS",
    "Icibemba" => "ICI",
    "Food and Nutrition" => "FN",
    "Design and Technology" => "D&T",
    "Art and Design" => "A&D",
    "Literature in English" => "LIT",
    "Civic Education" => "CivEd"
];

$query = "SELECT students.studentid, students.student_name, students.phone, students.school, students.intake, 
                 results.course, results.ca, results.exam, results.term, results.year 
          FROM students 
          INNER JOIN results ON students.studentid = results.studentid 
          WHERE results.term = '$term' 
            AND results.year = '$year' 
            AND students.school = '$school' 
            AND students.intake = '$intake' 
            AND students.program = '$program' 
            AND students.phone != ''";

$result = mysqli_query($conn, $query);

if (!$result) {
    die("Query failed: " . mysqli_error($conn));
}

if (mysqli_num_rows($result) > 0) {
    $studentsData = [];

    while ($row = mysqli_fetch_assoc($result)) {
        $studentId = $row['studentid'];
        if (!isset($studentsData[$studentId])) {
            $studentsData[$studentId] = [
                'school' => $row['school'],
                'name' => $row['student_name'],
                'phone' => $row['phone'],
                'term' => $row['term'],
                'year' => $row['year'],
                'subjects' => []
            ];
        }

        $studentsData[$studentId]['subjects'][] = [
            'course' => $row['course'],
            'ca' => $row['ca'],
            'exam' => $row['exam']
        ];
    }

    $authToken = getAuthToken($apiKey, $apiSecret);
    $smsSent = false;

    foreach ($studentsData as $student) {
        if (empty($student['phone'])) {
            echo "No phone number for student {$student['name']}. Skipping SMS.<br>";
            continue;
        }

        if (strpos($student['phone'], '+26') === 0) {
            $student['phone'] = substr($student['phone'], 1);
        } elseif (strpos($student['phone'], '26') !== 0) {
            $student['phone'] = '26' . $student['phone'];
        }

        $header = "{$student['school']} - {$student['name']} Term: {$student['term']} {$student['year']} Results";
        $subjectMarks = [];

        foreach ($student['subjects'] as $subject) {
            $trimmedSubject = trim($subject['course']);
            $shortSubject = $subjectAbbreviations[$trimmedSubject] ?? $trimmedSubject;
            $totalMarks = $subject['ca'] + $subject['exam'];
            $subjectMarks[] = "{$shortSubject}:{$totalMarks}";
        }

        $message = $header . " - " . implode(", ", $subjectMarks);
        $recipients = $student['phone'];

        if ($authToken) {
            $result = sendSms($authToken, $senderId, $message, $recipients);
            $status = ($result['status'] == 'error') ? 'Failed' : 'Sent';

            $sentTime = date("Y-m-d H:i:s");
            $messageEscaped = mysqli_real_escape_string($conn, $message);

            $logQuery = "INSERT INTO sms_logs (term, year, sent_time, student_name, phone, message) 
                         VALUES ('{$student['term']}', '{$student['year']}', '$sentTime', '{$student['name']}', '{$student['phone']}', '$messageEscaped')";

            if (!mysqli_query($conn, $logQuery)) {
                echo "Error inserting log for student {$student['name']}: " . mysqli_error($conn) . "<br>";
            } else {
                header("location:smsac?sms=Results successfully Sent");
            }

            if ($status == 'Failed') {
                echo "Error sending SMS to {$student['name']}: {$result['message']}<br>";
            } else {
                $smsSent = true;
            }
        } else {
            echo "Failed to generate access token for sending SMS.";
        }
    }
} else {
    echo "No results found.";
}

mysqli_close($conn);
?>