Path : /home/vishqocm/pcib.in/admin/ajax/
File Upload :
Current File : /home/vishqocm/pcib.in/admin/ajax/verify_payment.php

<?php
// Start session
session_start();

// Check if user has admin privileges
if (!isset($_SESSION['role']) || ($_SESSION['role'] !== 'admin' && $_SESSION['role'] !== 'director')) {
    echo json_encode([
        'success' => false,
        'message' => 'Unauthorized access'
    ]);
    exit;
}

// Include database configuration
require_once '../../admin/database/db_config.php';

// Check if payment_id and status are provided
if (!isset($_POST['payment_id']) || empty($_POST['payment_id']) || 
    !isset($_POST['status']) || empty($_POST['status'])) {
    echo json_encode([
        'success' => false,
        'message' => 'Payment ID and status are required'
    ]);
    exit;
}

$payment_id = intval($_POST['payment_id']);
$status = $_POST['status'];
$admin_notes = isset($_POST['admin_notes']) ? $_POST['admin_notes'] : '';
$admin_id = $_SESSION['user_id'];

// Validate status value
$valid_statuses = ['verified', 'rejected'];
if (!in_array($status, $valid_statuses)) {
    echo json_encode([
        'success' => false,
        'message' => 'Invalid status value'
    ]);
    exit;
}

try {
    // Start transaction
    $conn->begin_transaction();
    
    // First, get payment details
    $payment_query = "SELECT p.user_id, p.course_id, p.amount, p.payment_method, p.transaction_id, 
                      u.email, u.first_name, c.title as course_title 
                      FROM payments p
                      JOIN users u ON p.user_id = u.id
                      JOIN courses c ON p.course_id = c.id
                      WHERE p.id = ?";
    $stmt = $conn->prepare($payment_query);
    $stmt->bind_param("i", $payment_id);
    $stmt->execute();
    $payment_result = $stmt->get_result();
    
    if ($payment_result->num_rows === 0) {
        throw new Exception('Payment record not found');
    }
    
    $payment = $payment_result->fetch_assoc();
    
    // Update payment status
    $update_query = "UPDATE payments SET 
                    status = ?, 
                    verified_by = ?, 
                    verification_date = NOW(), 
                    admin_notes = ? 
                    WHERE id = ?";
    $stmt = $conn->prepare($update_query);
    $stmt->bind_param("sisi", $status, $admin_id, $admin_notes, $payment_id);
    $result = $stmt->execute();
    
    if (!$result) {
        throw new Exception('Failed to update payment status: ' . $conn->error);
    }
    
    // If payment is verified, check if all payments for the course are completed
    if ($status === 'verified') {
        // Get course price
        $course_query = "SELECT price, discount_percent FROM courses WHERE id = ?";
        $stmt = $conn->prepare($course_query);
        $stmt->bind_param("i", $payment['course_id']);
        $stmt->execute();
        $course_result = $stmt->get_result();
        $course = $course_result->fetch_assoc();
        
        // Calculate course price with discount
        $price = $course['price'];
        if ($course['discount_percent'] > 0) {
            $discount = ($price * $course['discount_percent']) / 100;
            $price = $price - $discount;
        }
        
        // Get total verified payments for this user and course
        $total_query = "SELECT SUM(amount) as total_paid 
                       FROM payments 
                       WHERE user_id = ? AND course_id = ? AND status = 'verified'";
        $stmt = $conn->prepare($total_query);
        $stmt->bind_param("ii", $payment['user_id'], $payment['course_id']);
        $stmt->execute();
        $total_result = $stmt->get_result();
        $total_row = $total_result->fetch_assoc();
        $total_paid = $total_row['total_paid'];
        
        // If payment is complete (or exceeds the price), update the enrollment status to active if it's not already
        if ($total_paid >= $price) {
            $enrollment_query = "SELECT id, status FROM enrollments 
                               WHERE user_id = ? AND course_id = ? 
                               AND (status = 'pending' OR status = 'payment_pending')";
            $stmt = $conn->prepare($enrollment_query);
            $stmt->bind_param("ii", $payment['user_id'], $payment['course_id']);
            $stmt->execute();
            $enrollment_result = $stmt->get_result();
            
            if ($enrollment_result->num_rows > 0) {
                $enrollment = $enrollment_result->fetch_assoc();
                
                // Only update if current status is pending or payment_pending
                if ($enrollment['status'] === 'pending' || $enrollment['status'] === 'payment_pending') {
                    $update_enrollment = "UPDATE enrollments SET 
                                        status = 'active', 
                                        enrollment_date = NOW(),
                                        payment_completed = 1
                                        WHERE id = ?";
                    $stmt = $conn->prepare($update_enrollment);
                    $stmt->bind_param("i", $enrollment['id']);
                    $stmt->execute();
                    
                    // Log this activity
                    $activity_desc = "Enrollment #" . $enrollment['id'] . " for " . $payment['first_name'] . 
                                    " (" . $payment['email'] . ") updated to active status after payment verification";
                    $activity_query = "INSERT INTO activities (user_id, activity_type, description, created_at) 
                                      VALUES (?, 'enrollment_update', ?, NOW())";
                    $stmt = $conn->prepare($activity_query);
                    $stmt->bind_param("is", $admin_id, $activity_desc);
                    $stmt->execute();
                }
            }
        }
    }
    
    // Log this activity
    $admin_action = $status === 'verified' ? 'verified' : 'rejected';
    $activity_desc = "Payment #" . $payment_id . " for " . $payment['first_name'] . " (" . $payment['email'] . 
                    ") " . $admin_action . " - Amount: $" . $payment['amount'] . 
                    ", Method: " . $payment['payment_method'] . 
                    ", Transaction ID: " . $payment['transaction_id'];
    
    $activity_query = "INSERT INTO activities (user_id, activity_type, description, created_at) 
                     VALUES (?, 'payment_verification', ?, NOW())";
    $stmt = $conn->prepare($activity_query);
    $stmt->bind_param("is", $admin_id, $activity_desc);
    $stmt->execute();
    
    // Check if the email function file exists and include it
    $email_file = '../../admin/functions/email_functions.php';
    if (file_exists($email_file)) {
        include_once $email_file;
        
        // If the send_email function exists, send a notification to the user
        if (function_exists('send_email')) {
            $subject = "Payment " . ($status === 'verified' ? 'Verified' : 'Rejected') . " - " . $payment['course_title'];
            
            $message = "Dear " . $payment['first_name'] . ",\n\n";
            $message .= "Your payment of $" . $payment['amount'] . " for " . $payment['course_title'] . " has been " . 
                       ($status === 'verified' ? 'verified' : 'rejected') . ".\n\n";
            
            if ($status === 'verified') {
                $message .= "Thank you for your payment. You can now access your course content.\n\n";
            } else {
                $message .= "Reason: " . $admin_notes . "\n\n";
                $message .= "Please contact our support team for more information or to make a new payment.\n\n";
            }
            
            $message .= "Transaction ID: " . $payment['transaction_id'] . "\n";
            $message .= "Payment Method: " . $payment['payment_method'] . "\n\n";
            $message .= "Regards,\nThe Education Platform Team";
            
            send_email($payment['email'], $subject, $message);
        }
    }
    
    // Commit transaction
    $conn->commit();
    
    echo json_encode([
        'success' => true,
        'message' => 'Payment ' . ($status === 'verified' ? 'verified' : 'rejected') . ' successfully'
    ]);
    
} catch (Exception $e) {
    // Rollback transaction on error
    $conn->rollback();
    
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}
?>