<?php
// payment_verify.php
require_once __DIR__ . '/db.php';
require_once __DIR__ . '/auth.php';
require_once __DIR__ . '/razorpay_config.php'; // Keeping for constants but not using
session_start();
requireRole(['dancer','admin']);

// Handle UTR verification
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['verify_utr'])) {
    $reg_id = (int)($_POST['reg_id'] ?? 0);
    $action = $_POST['action'] ?? '';
    
    if ($reg_id <= 0) {
        header("Location: dancer_dashboard.php?err=invalid");
        exit;
    }
    
    // Get registration details
    $stmt = $pdo->prepare("SELECT r.*, c.title FROM competition_registrations r 
                          JOIN competitions c ON c.id = r.competition_id 
                          WHERE r.id=? AND r.user_id=?");
    $stmt->execute([$reg_id, $_SESSION['user_id']]);
    $reg = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$reg) {
        header("Location: dancer_dashboard.php?err=notfound");
        exit;
    }
    
    // Handle video upload
    if ($action === 'upload_video' && isset($_FILES['video_file']) && $reg['payment_status'] === 'pending') {
        $video_url = trim($_POST['video_url'] ?? '');
        $file_uploaded = false;
        
        // Handle file upload if provided
        if (isset($_FILES['video_file']) && $_FILES['video_file']['error'] === UPLOAD_ERR_OK) {
            $upload_dir = __DIR__ . '/uploads/videos/';
            if (!is_dir($upload_dir)) {
                mkdir($upload_dir, 0755, true);
            }
            
            $file_name = time() . '_' . basename($_FILES['video_file']['name']);
            $target_file = $upload_dir . $file_name;
            
            if (move_uploaded_file($_FILES['video_file']['tmp_name'], $target_file)) {
                $video_url = 'uploads/videos/' . $file_name;
                $file_uploaded = true;
            }
        }
        
        // If video URL is provided (either from form or file upload)
        if (!empty($video_url)) {
            $update = $pdo->prepare("UPDATE competition_registrations 
                                   SET video_link=?, video_submitted_at=NOW() 
                                   WHERE id=?");
            $update->execute([$video_url, $reg_id]);
            
            header("Location: dancer_dashboard.php?video=1");
            exit;
        } else {
            $error = "Please provide a valid video URL or upload a video file";
        }
    }
    
    // Display the verification page
    ?>
    <!DOCTYPE html>
    <html>
    <head>
      <meta charset="utf-8">
      <title>Payment Verification • <?= htmlspecialchars(SITE_TITLE) ?></title>
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <script src="https://cdn.tailwindcss.com"></script>
      <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
      <style>
        .payment-container {
          background: linear-gradient(135deg, #ff006e 0%, #3a86ff 100%);
          border-radius: 1rem;
          padding: 2rem;
          color: white;
          box-shadow: 0 10px 25px rgba(255, 0, 110, 0.3);
        }
        .submit-button {
          background: white;
          color: #ff006e;
          border: none;
          padding: 0.75rem 2rem;
          border-radius: 2rem;
          font-weight: 600;
          cursor: pointer;
          width: 100%;
          transition: all 0.3s ease;
        }
        .submit-button:hover {
          transform: translateY(-2px);
          box-shadow: 0 10px 25px rgba(255, 0, 110, 0.4);
        }
        .form-input {
          background: rgba(255, 255, 255, 0.9);
          border: none;
          border-radius: 0.5rem;
          padding: 0.75rem;
          width: 100%;
          margin-bottom: 1rem;
        }
      </style>
    </head>
    <body class="bg-gray-50 min-h-screen flex items-center justify-center p-4">
      <div class="payment-container max-w-md w-full">
        <div class="text-center">
          <h1 class="text-2xl font-bold mb-2">Payment Verification</h1>
          <div class="text-white/90 mb-4 text-lg"><?= htmlspecialchars($reg['title']) ?></div>
          <div class="text-2xl font-bold mb-6">UTR: <?= htmlspecialchars($reg['payment_ref']) ?></div>
          
          <div class="bg-white/10 rounded-lg p-4 mb-6">
            <h2 class="text-xl font-semibold mb-3">Upload Your Video</h2>
            <p class="mb-4">Your payment is being verified. You can upload your competition video now.</p>
            
            <?php if (isset($error)): ?>
              <div class="bg-red-500 text-white p-2 rounded mb-3"><?= htmlspecialchars($error) ?></div>
            <?php endif; ?>
            
            <form method="POST" enctype="multipart/form-data">
              <input type="hidden" name="reg_id" value="<?= $reg_id ?>">
              <input type="hidden" name="action" value="upload_video">
              
              <div class="mb-4">
                <label class="block text-left mb-2">Option 1: YouTube Video Link</label>
                <input type="text" name="video_url" placeholder="https://youtu.be/..." class="form-input text-gray-800">
              </div>
              
              <div class="mb-4">
                <label class="block text-left mb-2">Option 2: Upload Video File</label>
                <input type="file" name="video_file" accept="video/*" class="form-input text-gray-800">
              </div>
              
              <button type="submit" class="submit-button">
                <i class="fas fa-upload mr-2"></i> Submit Video
              </button>
            </form>
          </div>
          
          <div class="text-white/70 text-sm">
            <i class="fas fa-info-circle mr-1"></i> Your payment will be verified within 24 hours
            <br>
            <i class="fas fa-phone mr-1"></i> For payment issues, contact support
          </div>
        </div>
      </div>
    </body>
    </html>
    <?php
    exit;
}

// Handle admin verification of UTR
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['admin_verify']) && ($_SESSION['type'] ?? '') === 'admin') {
    $reg_id = (int)($_POST['reg_id'] ?? 0);
    $action = $_POST['verify_action'] ?? '';
    
    if ($reg_id <= 0) {
        header("Location: admin_dashboard.php?err=invalid");
        exit;
    }
    
    if ($action === 'approve') {
        $update = $pdo->prepare("UPDATE competition_registrations 
                               SET payment_status='paid', paid_at=NOW() 
                               WHERE id=?");
        $update->execute([$reg_id]);
        
        // Update payments table
        $stmt = $pdo->prepare("SELECT payment_ref FROM competition_registrations WHERE id=?");
        $stmt->execute([$reg_id]);
        $reg = $stmt->fetch(PDO::FETCH_ASSOC);
        
        $update = $pdo->prepare("UPDATE payments SET status='paid', paid_at=NOW() 
                               WHERE order_id=?");
        $update->execute(['UTR-' . $reg['payment_ref']]);
        
        header("Location: admin_dashboard.php?verified=1");
        exit;
    } elseif ($action === 'reject') {
        $reason = trim($_POST['reason'] ?? '');
        $update = $pdo->prepare("UPDATE competition_registrations 
                               SET payment_status='rejected', payment_ref=CONCAT(payment_ref, ' - REJECTED: ', ?) 
                               WHERE id=?");
        $update->execute([$reason, $reg_id]);
        
        header("Location: admin_dashboard.php?rejected=1");
        exit;
    }
}

// If no valid action, redirect to dashboard
header("Location: dancer_dashboard.php");
exit;