<?php
require_once __DIR__ . '/db.php';
require_once __DIR__ . '/auth.php';
require_once __DIR__ . '/razorpay_config.php';
requireRole(['choreo','admin']);

// Check if payment data exists
if (!isset($_POST['razorpay_payment_id'], $_POST['razorpay_order_id'], $_POST['razorpay_signature'])) {
    header('Location: choreographer.php?err=missing_data');
    exit;
}

 $payment_id = $_POST['razorpay_payment_id'];
 $order_id = $_POST['razorpay_order_id'];
 $signature = $_POST['razorpay_signature'];
 $reg_id = (int)($_POST['reg_id'] ?? 0);

// Get order details from Razorpay
 $ch = curl_init('https://api.razorpay.com/v1/orders/' . $order_id);
curl_setopt_array($ch, [
    CURLOPT_USERPWD => RAZORPAY_KEY_ID . ':' . RAZORPAY_KEY_SECRET,
    CURLOPT_RETURNTRANSFER => true
]);
 $res = curl_exec($ch);
 $http = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

if ($http !== 200) {
    header('Location: choreographer.php?err=order_failed');
    exit;
}

 $order = json_decode($res, true);

// Verify payment belongs to this registration
if ($order['notes']['type'] !== 'coach' || (int)$order['notes']['reg_id'] !== $reg_id) {
    header('Location: choreographer.php?err=invalid_order');
    exit;
}

// Verify Razorpay signature
 $generated_signature = hash_hmac('sha256', $order_id . "|" . $payment_id, RAZORPAY_KEY_SECRET);
if ($generated_signature !== $signature) {
    header('Location: choreographer.php?err=invalid_signature');
    exit;
}

// Check if payment was successful
if ($order['status'] !== 'paid') {
    header('Location: choreographer.php?err=payment_failed');
    exit;
}

// Get registration details
 $stmt = $pdo->prepare("
    SELECT id, user_id, payment_status 
    FROM competition_registrations 
    WHERE id = ?
");
 $stmt->execute([$reg_id]);
 $registration = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$registration) {
    header('Location: choreographer.php?err=invalid_registration');
    exit;
}

// Update registration payment status
 $upd = $pdo->prepare("
    UPDATE competition_registrations 
    SET payment_status='paid', payment_time=NOW()
    WHERE id=? AND payment_status != 'paid'
");
 $upd->execute([$reg_id]);

// Update payment record with actual payment details
 $upd_payment = $pdo->prepare("
    UPDATE payments 
    SET payment_id=?, status='paid', payment_time=NOW()
    WHERE order_id=? AND status='created'
");
 $upd_payment->execute([$payment_id, $order_id]);

// Log payment success
 $log = $pdo->prepare("
    INSERT INTO payment_logs 
    (reg_id, payment_id, order_id, amount, currency, status, timestamp)
    VALUES (?,?,?,?,?,?,NOW())
");
 $log->execute([
    $reg_id,
    $payment_id,
    $order_id,
    $order['amount'] / 100,
    $order['currency'],
    'success'
]);

// Redirect to success page
header('Location: choreographer.php?paid=1');
exit;
?>