<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

include('sms.php');
require '../admin/includes/connection.php'; // Contains $conn and ZP_API_KEY and ZP_BASE_URL
require 'config.php'; 

$course_code=$_GET['couid'];
$book_id=$_GET['book_id'];
$student_id=$_GET['sdid'];
$subject_id=$_GET['sbid'];
$msg = "";

$book1= mysqli_query($conn,"SELECT * FROM `exam_booking` WHERE subject_id='$subject_id' AND booking_id='$book_id' ")or die(mysqli_error());
$book = mysqli_fetch_array($book1);
$exam_name=$book['exam_name'];
$grand_total = $book['cost'];
$description1 = "Payment for the course of";
$description = "$description1 $exam_name";


$invoice1= mysqli_query($conn,"SELECT * FROM student_soes  WHERE  course='$course_code' AND student_id='$student_id';")or die(mysqli_error());
$invoice3 = mysqli_fetch_array($invoice1);
$student_name=$invoice3['student_name'];
$email=$invoice3['student_email_id'];
$student_contact_no= $invoice3['student_contact_no'];
$student_name=$invoice3['student_name'];
 

$orderData = [
    'order_id'    => uniqid('', true),
    'buyer_email' => $email,
    'buyer_name'  => $student_name,
    'disc'        => $description,
    'buyer_phone' => $student_contact_no, // Tanzanian format
     'amount'      => $grand_total,           
    //  'amount'      => 1000,         // Amount in TZS
    // 'webhook_url' => 'https://your-domain.com/webhook', // Replace with actual URL
    'webhook_url' => '../admin.php?page=webhook', // Replace with actual URL
];

$ch = curl_init(ZP_BASE_URL . '/mobile_money_tanzania');
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POST           => true,
    CURLOPT_HTTPHEADER     => [
        'Content-Type: application/json',
        'x-api-key: ' . ZP_API_KEY,
    ],
    CURLOPT_POSTFIELDS     => json_encode($orderData),
]);

$response = curl_exec($ch);

if ($response === false) {
    file_put_contents('error_log.txt', date('[Y-m-d H:i:s] ') . 'cURL Error: ' . curl_error($ch) . PHP_EOL, FILE_APPEND);
    exit('❌ Request failed. Check error_log.txt');
}

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

if ($httpCode !== 200) {
    file_put_contents('error_log.txt', date('[Y-m-d H:i:s] ') . "HTTP Error: {$httpCode} - {$response}" . PHP_EOL, FILE_APPEND);
    exit("❌ HTTP {$httpCode}: {$response}");
}

$data = json_decode($response, true);

if ($data['status'] === 'success') {
    // Extract order info
    $order_id    = $orderData['order_id'];
    $buyer_name  = $orderData['buyer_name'];
    $buyer_email = $orderData['buyer_email'];
    $buyer_phone = $orderData['buyer_phone'];
    $amount      = $orderData['amount'];
    $desc2      =  $orderData['disc']; 
    $status      = 'PENDING';
    
     
   $query1= mysqli_query($conn,"SELECT * FROM exam_invoice WHERE course_code='$course_code' AND student_id='$student_id'")or die(mysqli_error());
	$row1 = mysqli_fetch_array($query1);
	 $course_code1 = $row1['course_code'];  

	 if ($course_code == "$course_code1" ){

	$query=mysqli_query($conn,"UPDATE exam_invoice set order_id='$order_id'  WHERE course_code='$course_code' AND student_id='$student_id'");
	  if($query){ 
	     ?>
	      <script type="text/javascript"> 
	           alert("Please complete your payment via mobile wallet using the phone number registered on your academy profile. Once your payment is confirmed, you’ll receive an access code to start your exam");
	           window.location.href = '../admin.php?page=payment_code&eeYf=<?php echo $order_id?>&Id_2=<?php echo $course_code?>&book_id=<?php echo $book_id?>';
	        </script>
	        <?php  
	      }  
    	} else{ 
    // INSERT using prepared statement
    $stmt = $conn->prepare("INSERT INTO exam_invoice (student_id,order_id,amount,course_code,description,payment_status) VALUES (?, ?, ?, ?, ?, ?)");
    $stmt->bind_param("ssssss",$student_id, $order_id, $amount, $course_code, $desc2, $status);

    if ($stmt->execute()) {
        // $s_mobile = "255757660790";
        //       $message = "Cybercode Exam Confirmed: $buyer_name are requested the payment Code for $exam_name and For amount $amount verify the invoice";
        //       send_message($s_mobile, $message);
			$msg = "<div class='alert bg-success-gradient' style='word-spacing: 5px; color: white;'>We've received your Order and we are working on it.</div>";
           ?>
				      <script type="text/javascript">  
				           window.location.href = '../admin.php?page=payment_code&eeYf=<?php echo $order_id?>&Id_2=<?php echo $course_code?>&book_id=<?php echo $book_id?>';
				        </script>
				        <?php  
            } else {
                file_put_contents('error_log.txt', date('[Y-m-d H:i:s] ') . 'MySQL Insert Error: ' . $stmt->error . PHP_EOL, FILE_APPEND);
                $msg = "<div class='alert bg-danger-gradient' style='word-spacing: 5px; color: white;'>Something wrong went.</div>";
            }
    	}

    $stmt->close();
    $conn->close();
} else {
    // Zenopay responded with failure
    http_response_code(400);
    echo json_encode([
        'success' => false,
        'message' => $data['message'] ?? 'Unknown error from payment gateway',
        'response' => $data
    ]);
    // echo "❌ Payment gateway error: {$data['message']}\n";
}
?>
