<?php
// api/verify_payment.php
// API endpoint for administrators/instructors to verify or reject monthly payment slips.
// FIXED: Added notification logic for the student AND email notification.

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

if (session_status() == PHP_SESSION_NONE) {
  session_start();
}

// Ensure user is logged in AND is an admin or instructor
if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true || ($_SESSION['user_role'] !== 'admin' && $_SESSION['user_role'] !== 'instructor')) {
  http_response_code(403);
  echo json_encode(['success' => false, 'message' => 'Authentication required or not authorized.']);
  exit();
}

require_once '../config/database.php'; // Path to database connection
require_once '../vendor/autoload.php'; // Include PHPMailer via Composer
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

// --- 1. EMAIL NOTIFICATION FUNCTION ---
function sendPaymentDecisionEmail(array $student_data, string $decision, string $course_name, string $batch_name, string $details_message): bool {
    
    try {
        $mail = new PHPMailer(true);
        $mail->isSMTP();
        $mail->Host       = 'smtp.gmail.com';
        $mail->SMTPAuth   = true;
        // !!! REPLACE WITH YOUR SMTP CREDENTIALS !!!
        $mail->Username   = 'bazithali95@gmail.com'; 
        $mail->Password   = 'sqkt opow cvao fiac'; 
        // !!! END SMTP CONFIG !!!
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; 
        $mail->Port       = 587;
        
        $mail->setFrom('bazithali95@gmail.com', 'Orinsto LMS Administration');
        $mail->addAddress($student_data['email'], $student_data['full_name']);
        
        if ($decision === 'verified') {
            $subject = "✅ Payment Verified: Your Course Access is Updated";
            $header_color = '#28a745';
        } else {
            $subject = "❗ Payment Rejected: Action Required";
            $header_color = '#dc3545';
        }

        $body_content = "
            <p>Dear {$student_data['full_name']},</p>
            <h3 style='color: {$header_color}; margin-top: 15px;'>Your monthly payment slip has been processed.</h3>
            
            <p><strong>Course/Batch:</strong> {$course_name} / {$batch_name}</p>
            
            <div style='padding: 10px; margin-top: 15px; border-radius: 4px; border: 1px solid #ddd; background-color: #f9f9f9;'>
                $details_message
            </div>

            <p style='margin-top: 25px;'>If you have any questions, please contact our support team.</p>
        ";
        
        $mail->Subject = $subject;
        $mail->isHTML(true);
        $mail->Body = $body_content;
        $mail->AltBody = strip_tags($body_content);

        $mail->send();
        return true;

    } catch (Exception $e) {
        error_log("Payment Decision Email failed for student ID {$student_data['student_id']} ({$decision}). Mailer Error: {$mail->ErrorInfo}");
        return false;
    }
}
// --- END OF EMAIL NOTIFICATION FUNCTION ---

$input = json_decode(file_get_contents('php://input'), true);

$payment_id = filter_var($input['payment_id'] ?? null, FILTER_VALIDATE_INT);
$action = trim($input['action'] ?? ''); // 'verified' or 'rejected'
$admin_notes = trim($input['admin_notes'] ?? '');

// New input parameters for LMS Access control
$access_end_date = $input['access_end_date'] ?? null; // Null or YYYY-MM-DD
$lifetime_access = filter_var($input['lifetime_access'] ?? 0, FILTER_VALIDATE_INT); // 1 or 0

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

$current_user_id = $_SESSION['user_id'];
$current_user_role = $_SESSION['user_role'];

// --- 2. Basic Input Validation ---
if (!$payment_id || !in_array($action, ['verified', 'rejected'])) {
  $response['message'] = "Invalid payment ID or action.";
  http_response_code(400);
  echo json_encode($response);
  exit();
}

// Validate access date if attempting to verify without lifetime access
if ($action === 'verified' && $lifetime_access === 0 && !preg_match('/^\d{4}-\d{2}-\d{2}$/', $access_end_date)) {
  $response['message'] = "Invalid access end date format. Must be YYYY-MM-DD or select LIFETIME.";
  http_response_code(400);
  echo json_encode($response);
  exit();
}

// --- Notification variables initialization ---
$student_id_to_notify = null;
$notif_title = '';
$notif_message = '';
$email_details = '';

try {
  // --- 3. Verify Payment Existence and Authorization (Updated to get student_id and email) ---
  $stmt_check = $pdo->prepare("
    SELECT 
      mp.id, 
      mp.status, 
      mp.enrollment_id, 
      b.instructor_id,
      ce.student_id,
      u.full_name AS student_full_name,
      u.email AS student_email,
      c.course_name,
      b.batch_name
    FROM monthly_payments mp
    JOIN course_enrollments ce ON mp.enrollment_id = ce.id
    JOIN users u ON ce.student_id = u.id
    JOIN batches b ON ce.batch_id = b.id
    JOIN courses c ON b.course_id = c.id
    WHERE mp.id = ? LIMIT 1
  ");
  $stmt_check->execute([$payment_id]);
  $payment_info = $stmt_check->fetch(PDO::FETCH_ASSOC);

  if (!$payment_info) {
    $response['message'] = "Payment record not found.";
    http_response_code(404);
    echo json_encode($response);
    exit();
  }

  // Set the student ID for later notification
  $student_id_to_notify = $payment_info['student_id'];
  
  // Ensure it's currently 'uploaded' before trying to verify/reject
  if ($payment_info['status'] !== 'uploaded') {
    $response['message'] = "Payment is not in 'uploaded' status. Current status: " . htmlspecialchars($payment_info['status']);
    http_response_code(400);
    echo json_encode($response);
    exit();
  }

  // Authorization check: Instructor can only verify/reject payments for their assigned batches.
  if ($current_user_role === 'instructor' && $payment_info['instructor_id'] != $current_user_id) {
    $response['message'] = "You are not authorized to manage this payment.";
    http_response_code(403);
    echo json_encode($response);
    exit();
  }
  
  $enrollment_id = $payment_info['enrollment_id'];

  // Start a transaction for atomicity
  $pdo->beginTransaction();

  // --- 4. Update Payment Status ---
  $update_sql = "
    UPDATE monthly_payments
    SET status = ?,
      verified_by_user_id = ?,
      verified_at = NOW(),
      admin_notes = ?
    WHERE id = ?
  ";
  $stmt_update = $pdo->prepare($update_sql);

  // Prepare parameters based on action
  $new_status = $action;
  $notes_to_save = ($action === 'rejected') ? $admin_notes : null; // Clear notes if verifying

  if (!$stmt_update->execute([$new_status, $current_user_id, $notes_to_save, $payment_id])) {
    throw new Exception("Failed to update payment status in database.");
  }
  
  // --- POPULATE NOTIFICATION AND EMAIL VARIABLES ---
  if ($action === 'verified') {
    $notif_title = "💸 Payment Verified!";
    if ($lifetime_access === 1) {
      $notif_message = "Your payment slip has been verified, and you have been granted **LIFETIME ACCESS** to the course.";
      $email_details = "<p>Your payment has been successfully verified, and you now have **LIFETIME ACCESS** to the course materials. Congratulations!</p>";
    } else {
      $notif_message = "Your payment slip has been verified. Your course access has been extended until **{$access_end_date}**.";
      $email_details = "<p>Your payment has been successfully verified, and your access has been extended until **" . date('F d, Y', strtotime($access_end_date)) . "**. Please make your next payment before this date to ensure continuous access.</p>";
    }
  } else { // Rejected
    $notif_title = "⚠️ Payment Rejected";
    $notif_message = "Your submitted payment slip was rejected. Reason: " . (empty($admin_notes) ? 'Please contact support for details.' : htmlspecialchars($admin_notes));
    $email_details = "<p style='color: #dc3545; font-weight: bold;'>Reason for Rejection:</p><p style='padding: 10px; border: 1px dashed #dc3545; background-color: #fff0f0;'>" . htmlspecialchars($admin_notes) . "</p><p>Please contact our support team to resolve this issue and resubmit your payment proof.</p>";
  }
  // -------------------------------------------------------------

  // --- 5. Handle LMS_Access Update (Only on verification) ---
  if ($action === 'verified') {
    
    $final_access_end_date = ($lifetime_access === 1) ? NULL : $access_end_date;

    // Check if an lms_access record already exists for this enrollment
    $stmt_check_access = $pdo->prepare("SELECT id FROM lms_access WHERE enrollment_id = ?");
    $stmt_check_access->execute([$enrollment_id]);
    $access_record_exists = $stmt_check_access->fetchColumn();

    if ($access_record_exists) {
      // UPDATE existing access record (extending the period)
      $sql_access = "
        UPDATE lms_access SET 
          monthly_payment_id = ?,
          access_end_date = ?,
          lifetime_access = ?
        WHERE enrollment_id = ?
      ";
      $stmt_access = $pdo->prepare($sql_access);
      $stmt_access->execute([$payment_id, $final_access_end_date, $lifetime_access, $enrollment_id]);
    } else {
      // INSERT new access record
      $sql_access = "
        INSERT INTO lms_access 
          (enrollment_id, monthly_payment_id, access_start_date, access_end_date, lifetime_access)
        VALUES (?, ?, CURDATE(), ?, ?)
      ";
      $stmt_access = $pdo->prepare($sql_access);
      $stmt_access->execute([$enrollment_id, $payment_id, $final_access_end_date, $lifetime_access]);
    }
  }
  // -------------------------------------------------------------

  // --- 6. NOTIFICATION INSERTION ---
  if (!empty($notif_title) && $student_id_to_notify) {
    $sql_notify = "
      INSERT INTO notifications (user_id, type, title, message, related_id)
      VALUES (?, 'payment_status', ?, ?, ?)
    ";
    $stmt_notify = $pdo->prepare($sql_notify);
    $stmt_notify->execute([
      $student_id_to_notify, 
      $notif_title, 
     $notif_message, 
$payment_id
]);
}
 // ---------------------------------------------

    // --- 7. SEND EMAIL AFTER ALL DB OPERATIONS ARE COMPLETE ---
    $student_info = [
        'full_name' => $payment_info['student_full_name'],
        'email' => $payment_info['student_email'],
        'student_id' => $student_id_to_notify
    ];
    
    $email_sent = sendPaymentDecisionEmail(
        $student_info, 
        $action, 
        $payment_info['course_name'], 
        $payment_info['batch_name'], 
        $email_details
    );
    
    if (!$email_sent) {
        // Log the failure but don't stop the process
        error_log("Failed to send student decision email for PID: {$payment_id}");
        $response['message'] .= " (Warning: Student email notification failed to send.)";
    }

 $pdo->commit(); // Commit the transaction
$response['success'] = true;
$response['message'] = "Payment " . htmlspecialchars($action) . " successfully and student notified.";

} catch (Exception $e) {
if ($pdo->inTransaction()) {
$pdo->rollBack(); // Rollback if something went wrong during transaction
}
$response['message'] = "Server error: " . $e->getMessage();
error_log("Verify Payment API Error: " . $e->getMessage());
http_response_code(500);
}

echo json_encode($response);
exit();