<?php
header('Content-Type: application/json');
require_once __DIR__ . '/../../common/journal_config_new.php';
require __DIR__ . '/razorpay-php/Razorpay.php';

use Razorpay\Api\Api;

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

$tracking_code = $input['tracking_code'] ?? '';
$payment_id = $input['razorpay_payment_id'] ?? '';
$order_id = $input['razorpay_order_id'] ?? '';
$signature = $input['razorpay_signature'] ?? '';

if (!$payment_id || !$tracking_code || !$order_id || !$signature) {
    http_response_code(400);
    echo json_encode(['success' => false, 'error' => 'Missing payment details']);
    exit;
}

try {
    $api = new Api(RAZORPAY_KEY_ID, RAZORPAY_SECRET);
    
    // Verify signature (IMPORTANT for security)
    $attributes = [
        'razorpay_order_id' => $order_id,
        'razorpay_payment_id' => $payment_id,
        'razorpay_signature' => $signature
    ];
    
    $api->utility->verifyPaymentSignature($attributes);
    
    // Fetch payment details from Razorpay
    $payment = $api->payment->fetch($payment_id);
    
    // Extract actual payment details from Razorpay response
    $actual_amount = $payment['amount'] / 100; // Convert from smallest unit to main unit
    $actual_currency = strtoupper($payment['currency']);
    $payer_email = $payment['email'] ?? '';
    $payer_name = $payment['contact'] ?? '';
    
    // If contact is a phone number, try to get name from notes
    if (isset($payment['notes']['name'])) {
        $payer_name = $payment['notes']['name'];
    }
    
    // Check if submission exists and get IDs
    $stmt = $pdo->prepare("SELECT id, author_id, fee_paid FROM submissions WHERE tracking_code = ? LIMIT 1");
    $stmt->execute([$tracking_code]);
    $submission = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$submission) {
        http_response_code(404);
        echo json_encode(['success' => false, 'error' => 'Submission not found']);
        exit;
    }
    
    if ($submission['fee_paid'] == 1) {
        echo json_encode(['success' => true, 'message' => 'Payment already recorded']);
        exit;
    }
    
    // Check if payment already exists in paypal_payments table (using capture_id)
    $check_stmt = $pdo->prepare("SELECT id FROM paypal_payments WHERE capture_id = ?");
    $check_stmt->execute([$payment_id]);
    
    if ($check_stmt->fetch()) {
        echo json_encode(['success' => true, 'message' => 'Payment already recorded']);
        exit;
    }
    
    // Prepare combined raw response
    $raw_combined = json_encode([
        "input"   => $input,
        "payment" => json_decode(json_encode($payment), true)
    ]);
    
    $invoice_no = "RSIS-" . $tracking_code;
    $payment_method = "razorpay";
    $status = ($payment['status'] === 'captured' || $payment['status'] === 'authorized') ? 'COMPLETED' : strtoupper($payment['status']);
    
    // Insert payment record into paypal_payments table
    $insert_stmt = $pdo->prepare("
        INSERT INTO paypal_payments 
        (tracking_code, invoice_no, payment_method, order_id, capture_id, status, 
         payer_email, payer_name, amount, currency, raw_response, author_id, submission_id)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
    ");
    
    $insert_stmt->execute([
        $tracking_code,
        $invoice_no,
        $payment_method,
        $order_id,
        $payment_id,    // capture_id = payment_id for Razorpay
        $status,
        $payer_email,
        $payer_name,
        $actual_amount,
        $actual_currency,
        $raw_combined,
        $submission['author_id'],
        $submission['id']
    ]);
    
    // Update submission fee_paid status
    $update_stmt = $pdo->prepare("
        UPDATE submissions 
        SET fee_paid = 1, payment_date = NOW(), updated_at = NOW() 
        WHERE tracking_code = ?
    ");
    $update_stmt->execute([$tracking_code]);
    
    echo json_encode([
        'success' => true,
        'payment_id' => $payment_id,
        'order_id' => $order_id,
        'status' => $status,
        'amount' => $actual_amount,
        'currency' => $actual_currency
    ]);
    
} catch (\Razorpay\Api\Errors\SignatureVerificationError $e) {
    http_response_code(400);
    echo json_encode([
        'success' => false,
        'error' => 'Payment signature verification failed: ' . $e->getMessage()
    ]);
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'error' => $e->getMessage()
    ]);
}
?>