<?php
// Demo.php - PhonePe Link Generation for Mobile App
// This file generates PhonePe payment links and stores them in database

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

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

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

// Initialize database
define('INITIALIZE_DB', true);
initializeDatabase();

// Get database connection
$pdo = getDBConnection();

// Function to generate PhonePe payment link
function generatePhonePeLink($amount, $mobile, $appointmentId, $pdo, $customerName = 'App User', $email = 'user@example.com', $description = 'Payment for AstroSidhi Services') {
    try {
        // PhonePe Production Credentials (Your actual credentials)
        $CLIENT_ID = "SU2509232050194428161935";
        $CLIENT_VERSION = "1";
        $CLIENT_SECRET = "ac7d0d8f-8bb1-45c4-baab-5f6f5e6ac3a2";
        
        // PhonePe API URLs (Production)
        $AUTH_URL = 'https://api.phonepe.com/apis/identity-manager/v1/oauth/token';
        $PAY_URL = 'https://api.phonepe.com/apis/pg/checkout/v2/pay';
        
        // Generate unique transaction ID
        $merchantOrderId = 'ASTRO-' . time() . '-' . rand(1000, 9999);
        
        // Convert amount to paise
        $amountPaise = intval($amount * 100);
        
        // Get OAuth token
        $token = getOAuthToken($AUTH_URL, $CLIENT_ID, $CLIENT_VERSION, $CLIENT_SECRET);
        
        if (!$token) {
            throw new Exception('Failed to get OAuth token');
        }
        
        // Create payment request
        $paymentData = [
            'merchantOrderId' => $merchantOrderId,
            'amount' => $amountPaise,
            'customer' => [
                'name' => $customerName,
                'mobile' => $mobile,
                'email' => $email
            ],
            'description' => $description,
            'paymentFlow' => [
                'type' => 'PG_CHECKOUT',
                'merchantUrls' => [
                    'webhookUrl' => 'https://astro.siddharthnahar.in/phonepe_webhook.php',
                    'successUrl' => 'https://astro.siddharthnahar.in/phonepe_success.php',
                    'failureUrl' => 'https://astro.siddharthnahar.in/phonepe_success.php'
                ]
            ]
        ];
        
        // Make API call to PhonePe
        $response = makePhonePeAPICall($PAY_URL, $paymentData, $token);
        
        // Debug logging
        error_log("PhonePe API Response: " . json_encode($response));
        
        if (!$response) {
            throw new Exception('No response from PhonePe API');
        }
        
        if (!isset($response['redirectUrl'])) {
            throw new Exception('No redirectUrl in response: ' . json_encode($response));
        }
        
        // Always create a new appointment for payment
        $createAppointmentStmt = $pdo->prepare("
            INSERT INTO appointments (
                user_id, 
                user_name,
                user_mobile,
                appointment_date, 
                time_slot, 
                amount, 
                consultation_type, 
                status, 
                payment_status,
                created_at
            ) VALUES (1, ?, ?, CURDATE(), '10:00-11:00', ?, 'video_call', 'pending', 'pending', NOW())
        ");
        $createAppointmentStmt->execute([$customerName, $mobile, $amount]);
        $appointmentId = $pdo->lastInsertId();
        error_log("Created new appointment with ID: $appointmentId for customer: $customerName, mobile: $mobile");
        
        // Store payment record in database with raw PhonePe response
        $stmt = $pdo->prepare("
            INSERT INTO payments (
                transaction_id, 
                appointment_id, 
                amount, 
                status, 
                payment_method, 
                payment_id, 
                phonepe_response, 
                created_at
            ) VALUES (?, ?, ?, 'PENDING', 'PHONEPE', ?, ?, NOW())
        ");
        
        $stmt->execute([
            $merchantOrderId,
            $appointmentId,
            $amount,
            $response['orderId'] ?? null,
            json_encode($response) // Raw PhonePe response as it is
        ]);
        
        // Auto-open URL on server (for testing)
        if (isset($response['redirectUrl'])) {
            // Log the URL for server-side opening
            error_log("PhonePe URL Generated: " . $response['redirectUrl']);
            
            // Try to open URL on server (if possible)
            if (function_exists('exec') && !empty($response['redirectUrl'])) {
                // For Linux/Unix servers
                if (PHP_OS_FAMILY === 'Linux') {
                    exec("xdg-open '" . $response['redirectUrl'] . "' > /dev/null 2>&1 &");
                }
                // For Windows servers
                elseif (PHP_OS_FAMILY === 'Windows') {
                    exec("start " . escapeshellarg($response['redirectUrl']));
                }
            }
        }
        
        return [
            'success' => true,
            'message' => 'Payment link generated successfully',
            'transactionId' => $merchantOrderId,
            'orderId' => $response['orderId'] ?? 'N/A',
            'amount' => $amount,
            'status' => $response['state'] ?? 'PENDING',
            'paymentUrl' => $response['redirectUrl'] ?? '',
            'redirectUrl' => $response['redirectUrl'] ?? '',
            'appointmentId' => $appointmentId,
            'data' => [
                'transactionId' => $merchantOrderId,
                'orderId' => $response['orderId'] ?? 'N/A',
                'amount' => $amount,
                'status' => $response['state'] ?? 'PENDING',
                'paymentUrl' => $response['redirectUrl'] ?? '',
                'redirectUrl' => $response['redirectUrl'] ?? '',
                'appointmentId' => $appointmentId
            ],
            'phonepeResponse' => $response, // Return complete PhonePe response
            'urlOpened' => isset($response['redirectUrl']) ? 'Attempted to open on server' : 'No URL to open'
        ];
        
    } catch (Exception $e) {
        error_log("PhonePe Link Generation Error: " . $e->getMessage());
        return [
            'success' => false,
            'error' => $e->getMessage()
        ];
    }
}

// Function to get OAuth token
function getOAuthToken($authUrl, $clientId, $clientVersion, $clientSecret) {
    $cacheFile = sys_get_temp_dir() . '/phonepe_oauth_token.json';
    
    // Check cache first
    if (file_exists($cacheFile)) {
        $cached = json_decode(file_get_contents($cacheFile), true);
        if (!empty($cached['access_token']) && $cached['expires_at'] > time() + 60) {
            return $cached['access_token'];
        }
    }
    
    // Get new token
    $postData = http_build_query([
        'client_id' => $clientId,
        'client_version' => $clientVersion,
        'client_secret' => $clientSecret,
        'grant_type' => 'client_credentials'
    ]);
    
    $ch = curl_init($authUrl);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => $postData,
        CURLOPT_HTTPHEADER => ['Content-Type: application/x-www-form-urlencoded'],
        CURLOPT_TIMEOUT => 15,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_SSL_VERIFYHOST => false
    ]);
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    
    if ($httpCode === 200) {
        $data = json_decode($response, true);
        if (isset($data['access_token'])) {
            $data['expires_at'] = time() + ($data['expires_in'] ?? 3600);
            file_put_contents($cacheFile, json_encode($data));
            return $data['access_token'];
        }
    }
    
    return false;
}

// Function to make PhonePe API call
function makePhonePeAPICall($url, $data, $token) {
    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => json_encode($data),
        CURLOPT_HTTPHEADER => [
            'Content-Type: application/json',
            'Authorization: O-Bearer ' . $token,
            'X-Version: 2.0',
            'X-Request-ID: ' . uniqid()
        ],
        CURLOPT_TIMEOUT => 15,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_SSL_VERIFYHOST => false
    ]);
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $error = curl_error($ch);
    curl_close($ch);
    
    // Debug logging
    error_log("PhonePe API Call - URL: $url");
    error_log("PhonePe API Call - HTTP Code: $httpCode");
    error_log("PhonePe API Call - Response: $response");
    if ($error) {
        error_log("PhonePe API Call - Error: $error");
    }
    
    if ($httpCode === 200) {
        $decoded = json_decode($response, true);
        if (json_last_error() !== JSON_ERROR_NONE) {
            error_log("JSON Decode Error: " . json_last_error_msg());
            return false;
        }
        return $decoded;
    }
    
    return false;
}

// Handle GET request for direct URL opening
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    // Simple form for testing
    ?>
    <!DOCTYPE html>
    <html>
    <head>
        <title>PhonePe Link Generator</title>
        <style>
            body { font-family: Arial, sans-serif; margin: 40px; }
            .form-group { margin: 15px 0; }
            input, button { padding: 10px; margin: 5px; }
            button { background: #007bff; color: white; border: none; cursor: pointer; }
        </style>
    </head>
    <body>
        <h2>PhonePe Link Generator</h2>
        <form method="POST">
            <div class="form-group">
                <label>Amount (₹):</label>
                <input type="number" name="amount" value="500" required>
            </div>
            <div class="form-group">
                <label>Mobile:</label>
                <input type="tel" name="mobile" value="9999999999" required>
            </div>
            <div class="form-group">
                <label>Appointment ID:</label>
                <input type="number" name="appointmentId" value="1" required>
            </div>
            <button type="submit">Generate & Open PhonePe Link</button>
        </form>
    </body>
    </html>
    <?php
    exit;
}

// Handle POST request
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        // Read from JSON input (for mobile app) or form data (for web testing)
        $input = null;
        $contentType = $_SERVER['CONTENT_TYPE'] ?? '';
        
        if (strpos($contentType, 'application/json') !== false) {
            // JSON input from mobile app
            $input = json_decode(file_get_contents('php://input'), true);
        } else {
            // Form data from web testing
            $input = $_POST;
        }
        
        if (!$input) {
            throw new Exception('Invalid input data');
        }
        
        // Handle Flutter app request format
        if (isset($input['action']) && $input['action'] === 'create_payment') {
            $amount = isset($input['amount']) ? floatval($input['amount']) : 0;
            $mobile = isset($input['mobile']) ? htmlspecialchars($input['mobile'], ENT_QUOTES, 'UTF-8') : '';
            $customerName = isset($input['customerName']) ? htmlspecialchars($input['customerName'], ENT_QUOTES, 'UTF-8') : 'App User';
            $email = isset($input['email']) ? htmlspecialchars($input['email'], ENT_QUOTES, 'UTF-8') : 'user@example.com';
            $description = isset($input['description']) ? htmlspecialchars($input['description'], ENT_QUOTES, 'UTF-8') : 'Payment for AstroSidhi Services';
        } else {
            // Handle direct API calls
            $amount = isset($input['amount']) ? floatval($input['amount']) : 0;
            $mobile = isset($input['mobile']) ? htmlspecialchars($input['mobile'], ENT_QUOTES, 'UTF-8') : '';
            $customerName = 'App User';
            $email = 'user@example.com';
            $description = 'Payment for AstroSidhi Services';
        }

        if ($amount <= 0) {
            throw new Exception('Invalid amount');
        }

        if (empty($mobile)) {
            throw new Exception('Mobile number is required');
        }

        // Generate PhonePe link (appointmentId will be created inside the function)
        $result = generatePhonePeLink($amount, $mobile, 0, $pdo, $customerName, $email, $description);

        // If it's a form submission (not JSON), redirect to the payment URL
        if (strpos($contentType, 'application/json') === false && $result['success']) {
            $paymentUrl = $result['data']['paymentUrl'] ?? $result['paymentUrl'] ?? '';
            if ($paymentUrl) {
                header('Location: ' . $paymentUrl);
                exit;
            }
        }

        echo json_encode($result, JSON_UNESCAPED_SLASHES);

    } catch (Exception $e) {
        http_response_code(400);
        echo json_encode([
            'success' => false,
            'error' => htmlspecialchars($e->getMessage(), ENT_QUOTES, 'UTF-8')
        ], JSON_UNESCAPED_SLASHES);
    }
} else {
    http_response_code(405);
    echo json_encode([
        'success' => false,
        'error' => 'Method not allowed'
    ], JSON_UNESCAPED_SLASHES);
}
?>