<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    exit(0);
}

require_once '../config/database.php';

try {
    // Get payment data from PhonePe callback
    $input = file_get_contents('php://input');
    $data = json_decode($input, true);
    
    // Debug: Log all received data
    error_log("Payment Callback - Raw Input: " . $input);
    error_log("Payment Callback - Decoded Data: " . print_r($data, true));
    error_log("Payment Callback - POST Data: " . print_r($_POST, true));
    error_log("Payment Callback - GET Data: " . print_r($_GET, true));
    
    // If no JSON data, try form data
    if (!$data) {
        $data = $_POST;
    }
    
    // If still no data, try GET parameters
    if (!$data) {
        $data = $_GET;
    }
    
    if (!$data) {
        throw new Exception('No payment data received');
    }
    
    // Extract data from PhonePe webhook structure
    $transactionId = null;
    $status = 'FAILED';
    $amount = 0;
    $paymentId = null;
    $appointmentId = null;
    
    // Handle PhonePe webhook structure
    if (isset($data['payload'])) {
        $payload = $data['payload'];
        $status = $payload['state'] ?? 'FAILED';
        // Convert amount from paise to rupees (PhonePe sends amount in paise)
        $amountPaise = $payload['amount'] ?? 0;
        $amount = $amountPaise / 100; // Convert paise to rupees
        
        // Debug: Log amount conversion
        error_log("Amount Conversion: {$amountPaise} paise = {$amount} rupees");
        $appointmentId = $payload['merchantOrderId'] ?? null;
        
        // Get transaction ID from payment details
        if (isset($payload['paymentDetails'][0]['transactionId'])) {
            $transactionId = $payload['paymentDetails'][0]['transactionId'];
        }
    } else {
        // Fallback to old structure
        $transactionId = $data['transactionId'] ?? $data['transaction_id'] ?? null;
        $status = $data['code'] ?? $data['status'] ?? 'FAILED';
        $amount = $data['amount'] ?? 0;
        $paymentId = $data['paymentId'] ?? $data['payment_id'] ?? null;
    }
    
    if (!$transactionId) {
        throw new Exception('Transaction ID not found in callback');
    }
    
    $pdo = getDBConnection();
    
    // Determine payment status
    $paymentStatus = 'FAILED';
    if ($status === 'PAYMENT_SUCCESS' || $status === 'SUCCESS' || $status === 'COMPLETED') {
        $paymentStatus = 'SUCCESS';
    } elseif ($status === 'PAYMENT_PENDING' || $status === 'PENDING') {
        $paymentStatus = 'PENDING';
    }
    
    error_log("Payment Status: $paymentStatus (from status: $status)");
    error_log("Amount Details: Original={$amountPaise} paise, Converted={$amount} rupees");
    
    // Create payment tracking record (always create new entry for each webhook call)
    $stmt = $pdo->prepare("
        INSERT INTO payment_tracking (
            transaction_id,
            merchant_order_id,
            order_id,
            amount,
            status,
            payment_method,
            phonepe_response,
            webhook_called_at,
            webhook_response,
            created_at
        ) VALUES (?, ?, ?, ?, ?, 'PHONEPE', ?, NOW(), ?, NOW())
    ");
    
    $stmt->execute([
        $transactionId,
        $appointmentId, // merchantOrderId
        $data['payload']['orderId'] ?? null,
        $amount,
        $paymentStatus,
        json_encode($data), // phonepe_response
        json_encode($data)  // webhook_response
    ]);
    
    // Also update existing payments table for backward compatibility
    $stmt = $pdo->prepare("
        INSERT INTO payments (
            transaction_id, 
            appointment_id, 
            amount, 
            status, 
            payment_method, 
            payment_id,
            phonepe_response,
            created_at
        ) VALUES (?, ?, ?, ?, 'PHONEPE', ?, ?, NOW())
        ON DUPLICATE KEY UPDATE
            status = VALUES(status),
            amount = VALUES(amount),
            payment_id = VALUES(payment_id),
            phonepe_response = VALUES(phonepe_response),
            updated_at = NOW()
    ");
    
    $stmt->execute([
        $transactionId,
        null, // appointment_id - will be null for now
        $amount,
        $paymentStatus,
        $paymentId,
        json_encode($data)
    ]);
    
    // If payment successful, update appointment status
    if ($paymentStatus === 'SUCCESS') {
        error_log("Payment is SUCCESS, attempting to update appointment...");
        
        // Try to get appointment ID from merchantOrderId or appointment_id
        $targetAppointmentId = $appointmentId ?? $data['appointment_id'] ?? null;
        
        error_log("Target appointment ID: $targetAppointmentId");
        
        if ($targetAppointmentId) {
            // Extract numeric ID from merchantOrderId (remove TXN_ prefix if present)
            $numericId = preg_replace('/^TXN_/', '', $targetAppointmentId);
            
            error_log("Extracted numeric ID: $numericId");
            
            // Check if appointment exists first
            $checkStmt = $pdo->prepare("SELECT id, status FROM appointments WHERE id = ?");
            $checkStmt->execute([$numericId]);
            $appointment = $checkStmt->fetch(PDO::FETCH_ASSOC);
            
            if ($appointment) {
                error_log("Found appointment: ID={$appointment['id']}, Status={$appointment['status']}");
                
                $stmt = $pdo->prepare("
                    UPDATE appointments 
                    SET status = 'confirmed', 
                        payment_status = 'paid',
                        updated_at = NOW()
                    WHERE id = ? AND status IN ('pending', 'pending_payment')
                ");
                $result = $stmt->execute([$numericId]);
                $affectedRows = $stmt->rowCount();
                
                error_log("Update result: " . ($result ? 'success' : 'failed') . ", Affected rows: $affectedRows");
                
                if ($affectedRows > 0) {
                    error_log("Successfully updated appointment ID: $numericId to confirmed status");
                } else {
                    error_log("No rows updated for appointment ID: $numericId (status may already be confirmed)");
                }
            } else {
                error_log("Appointment not found with ID: $numericId");
                
                // Try to find the most recent pending appointment
                $searchStmt = $pdo->prepare("
                    SELECT id, user_name, appointment_date, time_slot, status, created_at 
                    FROM appointments 
                    WHERE status IN ('pending', 'pending_payment') 
                    ORDER BY created_at DESC 
                    LIMIT 1
                ");
                $searchStmt->execute();
                $recentAppointment = $searchStmt->fetch(PDO::FETCH_ASSOC);
                
                if ($recentAppointment) {
                    error_log("Found recent pending appointment: ID={$recentAppointment['id']}, Name={$recentAppointment['user_name']}");
                    
                    // Update this appointment
                    $stmt = $pdo->prepare("
                        UPDATE appointments 
                        SET status = 'confirmed', 
                            payment_status = 'paid',
                            updated_at = NOW()
                        WHERE id = ?
                    ");
                    $result = $stmt->execute([$recentAppointment['id']]);
                    $affectedRows = $stmt->rowCount();
                    
                    if ($affectedRows > 0) {
                        error_log("Successfully updated recent appointment ID: {$recentAppointment['id']} to confirmed status");
                    }
                } else {
                    error_log("No recent pending appointments found");
                }
            }
        } else {
            error_log("No appointment ID found to update");
        }
    } else {
        error_log("Payment not successful, status: $paymentStatus");
    }
    
    // Log the callback
    error_log("PhonePe Callback: " . json_encode($data));
    
    echo json_encode([
        'success' => true,
        'message' => 'Payment callback processed',
        'transaction_id' => $transactionId,
        'status' => $paymentStatus
    ]);
    
} catch (Exception $e) {
    error_log("Payment callback error: " . $e->getMessage());
    http_response_code(400);
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
} catch (PDOException $e) {
    error_log("Payment callback database error: " . $e->getMessage());
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'Database error: ' . $e->getMessage()
    ]);
}
?>
