<?php
include('sms.php');
include ('../includes/connection.php');
require 'config.php';

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

 
require '../orbital/vendor/autoload.php';
$book_id=$_GET['book_id'];
$student_id=$user_row['student_id'];
$course_code=$user_row['course'];
$student_name = $user_row['student_name'];
$s_mobile     = $user_row['student_contact_no'];
$student_email_id = $user_row['student_email_id'];

// ✅ Retrieve student info for order
$query1 = mysqli_query($conn, "SELECT * FROM exam_invoice   WHERE student_id='$student_id' AND course_code='$course_code'") or die(mysqli_error($conn));

if (mysqli_num_rows($query1) == 0) {
    http_response_code(404);
    exit("❌ No invoice found for Order ID: $order_id");
}

$row1 = mysqli_fetch_array($query1);
 
$orderId = $row1['order_id'];

$url = ZP_BASE_URL . '/order-status?order_id=' . urlencode($orderId);

$ch = curl_init($url);
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER     => [
        'x-api-key: ' . ZP_API_KEY,
    ],
]);

$response = curl_exec($ch);
if ($response === false) {
    exit('cURL Error: ' . curl_error($ch));
}

$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode !== 200) {
    exit("HTTP {$httpCode}: {$response}");
}

$data = json_decode($response, true);
if (!empty($data['data']) && $data['result'] === 'SUCCESS') {
    foreach ($data['data'] as $order) {
        // echo "🔎 Order ID: {$order['order_id']}\n";
        // echo "   Status: {$order['payment_status']}\n";
        // echo "   Amount: {$order['amount']} TZS\n";
        // echo "   Reference: {$order['reference']}\n";
        $order_id =$order['order_id'];
        $payment_code=substr(str_shuffle("0123456789abcdefghijklmnopqrstvwxyzABCDEFGHIJKLMNOPQRSTVWXYZ"), 0, 8); // Use from Zenopay or generate here if needed
        $payment_status = $order['payment_status']; 
 

if ($payment_status == 'COMPLETED') {

// ✅ Update payment_code and payment_status
$stmt = $conn->prepare("UPDATE exam_invoice SET payment_code=?, payment_status=? WHERE order_id=?");
$stmt->bind_param("sss", $payment_code, $payment_status, $order_id);

if ($stmt->execute()) {
    // ✅ Format phone number (if needed)
    $s_mobile = ltrim($s_mobile, '0');
    $s_mobile = "255$s_mobile";

    // ✅ Send SMS
    $message = "Cybercode: Your exam access code is $payment_code. Valid on your exam date only. Don't share it. For help: +255686969536";
    send_message($s_mobile, $message);
     ?>
      <script type="text/javascript"> 
           window.location.href = 'admin.php?page=payment_success&Id_2=<?php echo $user_row['course']; ?>';
        </script>
        <?php  

    // ✅ Send email
    $mail = new PHPMailer(true);
    try {
        $mail->isSMTP();
        $mail->Host       = 'mail.cybercode.co.tz';
        $mail->SMTPAuth   = true;
        $mail->Username   = 'support@cybercode.co.tz';
        $mail->Password   = 'CYBER@support@2024';
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;            //Enable implicit TLS encryption
        $mail->Port       = 587; 

        $mail->setFrom('support@cybercode.co.tz', 'Cybercode Academy');
        $mail->addAddress($student_email_id);

        $mail->isHTML(true);
        $mail->Subject = 'Exam Access Code Issued';
        $mail->Body = "
            Dear $student_name,<br><br>
            Your payment has been confirmed. Use the access code below to activate your upcoming examination:<br><br>
            <strong>Access Code: $payment_code </strong><br><br>
            Log in to the system and insert this code to activate the exam. This code is valid for your exam date only and cannot be reused or shared.<br><br>
            Best wishes,<br>
            Cybercode Academy Team
        ";

        $mail->send();
        echo "✅ Payment confirmed. Email and SMS sent.";
    } catch (Exception $e) {
        echo "❌ Email not sent. Error: {$mail->ErrorInfo}";
    }
} else {
    file_put_contents('weblogs.txt', date('[Y-m-d H:i:s] ') . '❌ DB Error: ' . $stmt->error . PHP_EOL, FILE_APPEND);
    http_response_code(500);
    exit('❌ Failed to update invoice');
}

$stmt->close();
$conn->close();
}else {
     ?>
      <script type="text/javascript"> 
          alert("Sorry Complete your Payment First");
           window.location.href = 'admin.php?page=payment_code&Id_2=<?php echo $user_row['course']; ?>&book_id=<?php echo $book_id; ?>';
        </script>
        <?php   
}

    }
} else {
      
    echo "❌ Error: {$data['message']}\n";
}
?>
