<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
header('Content-Type: application/json');

include('includes/dbconnection.php');

// Fetch active session
$currentSessionQuery = "
    SELECT id, session_name 
    FROM school_sessions 
    WHERE start_date <= CURDATE() 
      AND end_date >= CURDATE() 
    ORDER BY start_date ASC 
    LIMIT 1";
$currentSessionResult = $con->query($currentSessionQuery);

if ($currentSessionResult && $currentSessionResult->num_rows > 0) {
  $currentSession = $currentSessionResult->fetch_assoc();
  $currentSessionId = $currentSession['id'];
  $currentSessionName = $currentSession['session_name'];
} else {
  $currentSessionId = null;
  $currentSessionName = null;
}

// Fetch the current term
$termQuery = "SELECT id, term_name FROM school_terms 
              WHERE session_id = '$currentSessionId'
              AND start_date <= CURDATE() 
              AND end_date >= CURDATE() 
              ORDER BY start_date ASC 
              LIMIT 1";
$termResult = mysqli_query($con, $termQuery);
$termRow = mysqli_fetch_assoc($termResult);
$currentTermId = $termRow['id'] ?? null;
$currentTermName = $termRow['term_name'] ?? null;

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
  http_response_code(405);
  echo json_encode(['status' => 'error', 'message' => 'Invalid request method']);
  exit;
}

// Collect and sanitize inputs
$student_id = intval($_POST['stdid'] ?? 0);
$studentno = $_POST['studentno'] ?? null;
$studentName = $_POST['studentName'] ?? null;
$email = $_POST['email'] ?? null;
$amount = floatval(str_replace([',', '₦'], '', $_POST['payAmount'] ?? 0));
$status = 'pending';
$fee_type = $_POST['feeType'] ?? null;
$reference = $fee_type . '-' . date('Ymd-His') . '-' . bin2hex(random_bytes(5));
$payment_date = date('Y-m-d H:i:s');
$discount_used = $_POST['discount_used'] ?? 'No';
$discount_amount = floatval($_POST['discount_amount'] ?? 0);
$discount_percent = floatval($_POST['discount_percent'] ?? 0);
$payment_method = 'paystack';
$term_id = $_POST['term_id'] ?? $currentTermName;
$session_id = $_POST['session_id'] ?? $currentSessionName;
$class = $_POST['class'] ?? null;

$stmt = $con->prepare("INSERT INTO initiate_payment (
    student_id, studentno, studentName, email, reference, amount, status, fee_type, payment_date, 
    discount_used, discount_amount, discount_percent, payment_method, term_id, session_id, class
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");

if (!$stmt) {
  http_response_code(500);
  echo json_encode(['status' => 'error', 'message' => 'Prepare failed: ' . $con->error]);
  exit;
}

// 16 params: i s s s s d s s s s d d s s s s
$typeString = "issssdssssddssss";
$stmt->bind_param(
  $typeString,
  $student_id,
  $studentno,
  $studentName,
  $email,
  $reference,
  $amount,
  $status,
  $fee_type,
  $payment_date,
  $discount_used,
  $discount_amount,
  $discount_percent,
  $payment_method,
  $term_id,
  $session_id,
  $class
);

if ($stmt->execute()) {
  echo json_encode(['status' => 'success']);
} else {
  http_response_code(500);
  echo json_encode(['status' => 'error', 'message' => 'DB insert failed: ' . $stmt->error]);
}

$stmt->close();
$con->close();
