<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>MIRAMAX Media – Watch & Earn</title>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="csrf-token" content="<?php echo e(csrf_token()); ?>">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet">
<style>
:root{
  --bg:#0b0b0e; --card:#16161b; --soft:#1d1d24; --text:#e9e9ef;
  --muted:#a7a7b3; --brand:#5a43eb; --gold:#d9b872; --gold-2:#f5d293;
  --chip:#2a2a33; --shadow:0 6px 18px rgba(0,0,0,.35); --radius:16px;
}
*{box-sizing:border-box; margin:0; padding:0;}
body{background:var(--bg);color:var(--text);font-family:Inter,system-ui,sans-serif; line-height:1.4;}
.page{ max-width:800px; margin:0 auto; padding:20px 14px 80px; }
.back-btn{ display:inline-block; padding:8px 16px; font-size:14px; background:var(--soft); border:1px solid #333; border-radius:10px; color:#fff; box-shadow:var(--shadow); margin-bottom:20px; text-decoration:none;}
.back-btn:hover{background:var(--gold); color:#000;}
.video-title{ font-size:22px; font-weight:800; margin:0 0 16px; background:linear-gradient(180deg,var(--gold),var(--gold-2)); -webkit-background-clip:text; background-clip:text; color:transparent; text-align:center;}
.video-frame{ position:relative; width:100%; padding-bottom:56.25%; border-radius:var(--radius); overflow:hidden; background:#000; box-shadow:var(--shadow); margin-bottom:20px;}
.video-frame iframe{ position:absolute; top:0; left:0; width:100%; height:100%; border:0;}
#result{ margin-top:18px; font-size:16px; font-weight:600; text-align:center; color:var(--muted); }
#result span{color:var(--gold-2); font-weight:700;}
#countdown { margin-top:10px; font-size:16px; font-weight:bold; color:var(--gold-2);}
#unmuteBtn { display:inline-block; margin-top:8px; background:var(--brand); color:#fff; border:none; padding:8px 16px; border-radius:10px; cursor:pointer; font-weight:600;}
#unmuteBtn:hover { background:var(--gold); color:#000;}
@media(max-width:600px){
  .page{padding:16px 10px 60px;}
  .video-title{font-size:18px;}
  #countdown{font-size:14px;}
  #unmuteBtn{padding:6px 12px; font-size:14px;}
}
</style>
</head>
<body>
<div class="page">

  <!-- Back Button -->
  <a href="<?php echo e(url()->previous()); ?>" class="back-btn">⬅ Back</a>

  <!-- Video Title -->
  <h2 class="video-title">🎬 <?php echo e($video->title ?? 'Video'); ?></h2>

  <!-- Video Frame -->
  <div class="video-frame">
    <?php
      function getYouTubeID($url) {
          preg_match('/(?:youtube\.com\/(?:[^\/]+\/.+\/|(?:v|embed)\/|.*[?&]v=)|youtu\.be\/)([^"&?\/ ]{11})/i', $url, $matches);
          return $matches[1] ?? null;
      }
      $youtubeID = getYouTubeID($video->url ?? '');
    ?>

    <?php if(!$youtubeID): ?>
      <div id="result">⚠ Invalid video URL</div>
    <?php else: ?>
      <iframe id="videoIframe"
              src="https://www.youtube.com/embed/<?php echo e($youtubeID); ?>?autoplay=1&mute=1&controls=1&rel=0&modestbranding=1"
              allow="autoplay; fullscreen"
              allowfullscreen>
      </iframe>
    <?php endif; ?>
  </div>

  <!-- Countdown & Result -->
  <div class="text-center">
      <?php
          use App\Models\Purchase;
          use App\Models\Package;
          use App\Models\VideoView;

          $user = auth()->user();
          $canWatch = false;
          $message = '';
          $dailyEarning = 0;

          if(!$user){
              $message = "⚠ Please login to watch videos.";
          } else {
              $purchase = Purchase::where('user_id', $user->id)
                                  ->where('status','active')->first();
              if(!$purchase){
                  $message = "⚠ No active package!";
              } else {
                  $package = Package::find($purchase->package_id);
                  if(!$package){
                      $message = "⚠ Package missing!";
                  } else {
                      $expiryDate = $purchase->created_at->addDays($package->validity);
                      $watchedToday = VideoView::where('user_id', $user->id)
                                              ->whereDate('created_at', now())->count();

                      // Calculate daily earning dynamically
                      $totalPackageIncome = $package->commission_with_avg_amount ?? 0;
                      $validityDays = $package->validity ?? 1;
                      $dailyEarning = $totalPackageIncome / $validityDays;

                      // Calculate total earned so far
                      $totalEarned = VideoView::where('user_id', $user->id)
                                  ->whereBetween('created_at', [$purchase->created_at, $expiryDate])
                                  ->sum('earned_amount');

                      if(now()->gt($expiryDate)){
                          $message = "⚠ Package expired!";
                      } elseif($watchedToday >= $package->daily_watch_limit){
                          $message = "⚠ Daily watch limit reached!";
                      } elseif($totalEarned + $dailyEarning > $totalPackageIncome){
                          $message = "⚠ You have reached maximum earning for this package!";
                      } else {
                          $canWatch = true;
                      }
                  }
              }
          }
      ?>

      <?php if(!$canWatch): ?>
          <div id="result"><?php echo e($message); ?></div>
      <?php else: ?>
          <div id="countdown">Auto-earning in 15 seconds...</div>
          <div id="result" style="margin-top:15px; font-weight:bold;">You will earn <span>R<?php echo e(number_format($dailyEarning, 2)); ?></span> for this video.</div>
          <button id="unmuteBtn">Unmute Video</button>
          <form id="watchForm" method="POST" action="<?php echo e(route('video.watch', $video->id)); ?>">
              <?php echo csrf_field(); ?>
          </form>
      <?php endif; ?>
  </div>

</div>

<?php if($canWatch): ?>
<script>
document.addEventListener("DOMContentLoaded", function() {
    const countdownDiv = document.getElementById('countdown');
    const watchForm = document.getElementById('watchForm');
    const videoFrame = document.getElementById('videoIframe');
    const unmuteBtn = document.getElementById('unmuteBtn');

    // Unmute on button click
    unmuteBtn.addEventListener('click', function(){
        let src = videoFrame.src;
        if(src.indexOf('mute=1')!==-1){
            videoFrame.src = src.replace('mute=1','mute=0');
        }
        unmuteBtn.style.display = 'none';
    });

    // 15-second countdown auto-submit
    let timeLeft = 15;
    const timer = setInterval(() => {
        countdownDiv.textContent = "Auto-earning in " + timeLeft + " seconds...";
        timeLeft--;
        if(timeLeft < 0){
            clearInterval(timer);
            countdownDiv.textContent = "Processing earnings...";
            watchForm.submit();
        }
    }, 1000);
});
</script>
<?php endif; ?>

</body>
</html>
<?php /**PATH /home/ddmkeqvc/public_html/resources/views/app/main/video_show.blade.php ENDPATH**/ ?>