<?php
require_once __DIR__ . '/../../api/lib.php';
hw_require_auth(['coach']);
$authUser = hw_get_auth_user();

$page_title = 'Earnings & Commissions | Coach Dashboard';
$page_description = 'Track your earnings and commission payments';
$page_content = function () use ($authUser) {
$db = hw_db();

// Get coach data
$coachStmt = $db->prepare("SELECT * FROM coaches WHERE user_id = ?");
$coachStmt->execute([$authUser['id']]);
$coach = $coachStmt->fetch(PDO::FETCH_ASSOC);

if (!$coach) {
    echo '<div class="p-8 text-center"><p class="text-red-600">Coach profile not found.</p></div>';
    return;
}

// Get earnings from completed appointments
$earningsStmt = $db->prepare("
    SELECT 
        i.id,
        i.total_amount,
        i.status as payment_status,
        i.created_at as invoice_date,
        a.starts_at,
        a.ends_at,
        u.first_name,
        u.last_name,
        TIMESTAMPDIFF(MINUTE, a.starts_at, a.ends_at) as duration_minutes
    FROM invoices i
    JOIN appointments a ON DATE(i.created_at) = DATE(a.starts_at) AND i.user_id = a.user_id
    JOIN users u ON a.user_id = u.id
    WHERE a.coach_id = ? AND a.status = 'completed'
    ORDER BY i.created_at DESC
    LIMIT 50
");
$earningsStmt->execute([$coach['id']]);
$earnings = $earningsStmt->fetchAll(PDO::FETCH_ASSOC);

// Calculate totals
$totalEarnings = 0;
$paidEarnings = 0;
$pendingEarnings = 0;

foreach ($earnings as $earning) {
    $totalEarnings += $earning['total_amount'];
    if ($earning['payment_status'] === 'paid') {
        $paidEarnings += $earning['total_amount'];
    } else {
        $pendingEarnings += $earning['total_amount'];
    }
}

// Get this month's earnings
$monthStart = date('Y-m-01 00:00:00');
$monthEnd = date('Y-m-t 23:59:59');
$monthStmt = $db->prepare("
    SELECT SUM(i.total_amount) as month_total
    FROM invoices i
    JOIN appointments a ON DATE(i.created_at) = DATE(a.starts_at) AND i.user_id = a.user_id
    WHERE a.coach_id = ? AND i.status = 'paid' AND i.created_at BETWEEN ? AND ?
");
$monthStmt->execute([$coach['id'], $monthStart, $monthEnd]);
$monthEarnings = $monthStmt->fetch(PDO::FETCH_ASSOC)['month_total'] ?? 0;
?>

<style>
  nav.fixed { 
    display: none !important; 
    visibility: hidden !important;
    position: absolute !important;
    pointer-events: none !important;
    z-index: -1 !important;
  }
  body > nav { 
    display: none !important; 
    visibility: hidden !important;
  }
  body {
    padding-top: 0 !important;
  }
</style>
<link rel="stylesheet" href="/atasteofafricanmarketplace/assets/dashboard.css">

<div class="dashboard-container">
  <!-- Sidebar -->
  <div class="dashboard-sidebar">
    <div class="sidebar-header">
      <div class="sidebar-profile">
        <div class="profile-avatar" style="background: linear-gradient(135deg, #10b981, #059669);">
          <?= strtoupper(substr($coach['display_name'], 0, 2)) ?>
        </div>
        <div class="profile-info">
          <h3><?= htmlspecialchars($coach['display_name']) ?></h3>
          <p>Coach Portal</p>
        </div>
      </div>
    </div>
    <nav class="sidebar-nav">
      <a href="/atasteofafricanmarketplace/dashboard/coach/index.php"><i class="fas fa-home"></i>Overview</a>
      <a href="/atasteofafricanmarketplace/dashboard/coach/sessions.php"><i class="fas fa-calendar-check"></i>Sessions</a>
      <a href="/atasteofafricanmarketplace/dashboard/coach/clients.php"><i class="fas fa-users"></i>Clients</a>
      <a href="/atasteofafricanmarketplace/dashboard/coach/schedule.php"><i class="fas fa-clock"></i>Schedule</a>
      <a href="/atasteofafricanmarketplace/dashboard/coach/earnings.php" class="active"><i class="fas fa-dollar-sign"></i>Earnings</a>
      <hr class="sidebar-divider">
      <a href="/atasteofafricanmarketplace/index.php"><i class="fas fa-arrow-left"></i>Back to Home</a>
    </nav>
    <div class="sidebar-footer">
      <a href="/atasteofafricanmarketplace/api/auth/logout.php" style="display: flex; align-items: center; gap: 12px; color: rgba(255,255,255,0.7); text-decoration: none; font-size: 13px; font-weight: 500; padding: 10px 0; border-top: 1px solid rgba(212, 173, 49, 0.15); transition: all 0.3s;"><i class="fas fa-sign-out-alt"></i>Sign Out</a>
    </div>
  </div>

  <!-- Main Content -->
  <div class="dashboard-content">
    <main>
      <!-- Header -->
      <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 32px; flex-wrap: wrap; gap: 16px;">
        <div>
          <h1 style="font-size: 32px; font-weight: 800; color: #0b3d2e; margin: 0 0 8px 0;">Earnings & Commissions</h1>
          <p style="font-size: 16px; color: #64748b; margin: 0;">Track your income from coaching sessions</p>
        </div>
        <button onclick="requestPayout()" style="background: linear-gradient(135deg, #10b981, #059669); color: white; padding: 12px 24px; border-radius: 10px; font-size: 15px; font-weight: 700; border: none; cursor: pointer; transition: all 0.3s; box-shadow: 0 4px 12px rgba(16, 185, 129, 0.3); display: flex; align-items: center; gap: 8px;">
          <i class="fas fa-paper-plane"></i> Request Payout
        </button>
      </div>

      <!-- Summary Cards -->
      <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap: 20px; margin-bottom: 32px;">
        <div style="background: linear-gradient(135deg, #10b981, #059669); padding: 28px; border-radius: 16px; color: white; position: relative; overflow: hidden;">
          <div style="position: absolute; top: -30px; right: -30px; width: 120px; height: 120px; background: rgba(255, 255, 255, 0.1); border-radius: 50%;"></div>
          <div style="position: relative;">
            <div style="display: flex; justify-content: space-between; align-items: start; margin-bottom: 16px;">
              <div style="font-size: 13px; opacity: 0.9; font-weight: 600; text-transform: uppercase;">Total Earnings</div>
              <i class="fas fa-dollar-sign" style="font-size: 28px; opacity: 0.3;"></i>
            </div>
            <div id="total-earnings" style="font-size: 40px; font-weight: 800; line-height: 1;">$<?= number_format($totalEarnings, 2) ?></div>
            <div style="font-size: 13px; opacity: 0.85; margin-top: 8px;">All-time earnings</div>
          </div>
        </div>

        <div style="background: linear-gradient(135deg, #3b82f6, #2563eb); padding: 28px; border-radius: 16px; color: white; position: relative; overflow: hidden;">
          <div style="position: absolute; top: -30px; right: -30px; width: 120px; height: 120px; background: rgba(255, 255, 255, 0.1); border-radius: 50%;"></div>
          <div style="position: relative;">
            <div style="display: flex; justify-content: space-between; align-items: start; margin-bottom: 16px;">
              <div style="font-size: 13px; opacity: 0.9; font-weight: 600; text-transform: uppercase;">Paid Out</div>
              <i class="fas fa-check-circle" style="font-size: 28px; opacity: 0.3;"></i>
            </div>
            <div id="paid-earnings" style="font-size: 40px; font-weight: 800; line-height: 1;">$<?= number_format($paidEarnings, 2) ?></div>
            <div style="font-size: 13px; opacity: 0.85; margin-top: 8px;">Successfully paid</div>
          </div>
        </div>

        <div style="background: linear-gradient(135deg, #f59e0b, #d97706); padding: 28px; border-radius: 16px; color: white; position: relative; overflow: hidden;">
          <div style="position: absolute; top: -30px; right: -30px; width: 120px; height: 120px; background: rgba(255, 255, 255, 0.1); border-radius: 50%;"></div>
          <div style="position: relative;">
            <div style="display: flex; justify-content: space-between; align-items: start; margin-bottom: 16px;">
              <div style="font-size: 13px; opacity: 0.9; font-weight: 600; text-transform: uppercase;">Pending</div>
              <i class="fas fa-clock" style="font-size: 28px; opacity: 0.3;"></i>
            </div>
            <div id="pending-earnings" style="font-size: 40px; font-weight: 800; line-height: 1;">$<?= number_format($pendingEarnings, 2) ?></div>
            <div style="font-size: 13px; opacity: 0.85; margin-top: 8px;">Awaiting payout</div>
          </div>
        </div>

        <div style="background: linear-gradient(135deg, #8b5cf6, #7c3aed); padding: 28px; border-radius: 16px; color: white; position: relative; overflow: hidden;">
          <div style="position: absolute; top: -30px; right: -30px; width: 120px; height: 120px; background: rgba(255, 255, 255, 0.1); border-radius: 50%;"></div>
          <div style="position: relative;">
            <div style="display: flex; justify-content: space-between; align-items: start; margin-bottom: 16px;">
              <div style="font-size: 13px; opacity: 0.9; font-weight: 600; text-transform: uppercase;">This Month</div>
              <i class="fas fa-calendar" style="font-size: 28px; opacity: 0.3;"></i>
            </div>
            <div id="month-earnings" style="font-size: 40px; font-weight: 800; line-height: 1;">$<?= number_format($monthEarnings, 2) ?></div>
            <div style="font-size: 13px; opacity: 0.85; margin-top: 8px;"><?= date('F Y') ?></div>
          </div>
        </div>
      </div>

      <!-- Earnings History -->
      <div style="background: white; padding: 32px; border-radius: 16px; box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05); margin-bottom: 24px;">
        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 24px;">
          <div>
            <h2 style="font-size: 20px; font-weight: 700; color: #0b3d2e; margin: 0 0 4px 0;">Earnings History</h2>
            <p style="font-size: 14px; color: #64748b; margin: 0;">Your earnings from completed sessions</p>
          </div>
          <button onclick="exportEarnings()" style="background: white; color: #10b981; padding: 10px 20px; border-radius: 8px; font-size: 14px; font-weight: 600; border: 2px solid #10b981; cursor: pointer; transition: all 0.3s;">
            <i class="fas fa-download"></i> Export
          </button>
        </div>

        <?php if (empty($earnings)): ?>
          <div style="text-align: center; padding: 80px 20px; background: #f9fafb; border-radius: 12px;">
            <div style="width: 80px; height: 80px; background: linear-gradient(135deg, #e0f2fe, #dbeafe); border-radius: 50%; display: flex; align-items: center; justify-content: center; margin: 0 auto 20px;">
              <i class="fas fa-dollar-sign" style="font-size: 36px; color: #3b82f6;"></i>
            </div>
            <h3 style="font-size: 18px; font-weight: 700; color: #0b3d2e; margin: 0 0 8px 0;">No earnings yet</h3>
            <p style="color: #64748b; margin: 0;">Your earnings will appear here once clients pay for completed sessions</p>
          </div>
        <?php else: ?>
          <div style="overflow-x: auto;">
            <table style="width: 100%; border-collapse: collapse;">
              <thead>
                <tr style="background: #f9fafb; border-bottom: 2px solid #e5e7eb;">
                  <th style="text-align: left; padding: 16px; font-weight: 700; color: #374151; font-size: 13px; text-transform: uppercase;">Date</th>
                  <th style="text-align: left; padding: 16px; font-weight: 700; color: #374151; font-size: 13px; text-transform: uppercase;">Client</th>
                  <th style="text-align: left; padding: 16px; font-weight: 700; color: #374151; font-size: 13px; text-transform: uppercase;">Session</th>
                  <th style="text-align: left; padding: 16px; font-weight: 700; color: #374151; font-size: 13px; text-transform: uppercase;">Amount</th>
                  <th style="text-align: left; padding: 16px; font-weight: 700; color: #374151; font-size: 13px; text-transform: uppercase;">Status</th>
                </tr>
              </thead>
              <tbody>
                <?php foreach ($earnings as $earning): 
                  $invoiceDate = new DateTime($earning['invoice_date']);
                  $statusStyles = [
                    'paid' => 'background: #d1fae5; color: #065f46;',
                    'pending' => 'background: #fef3c7; color: #92400e;',
                    'failed' => 'background: #fee2e2; color: #991b1b;'
                  ];
                ?>
                  <tr style="border-bottom: 1px solid #e5e7eb; transition: all 0.2s;" onmouseover="this.style.background='#f9fafb'" onmouseout="this.style.background='white'">
                    <td style="padding: 20px 16px;">
                      <div style="font-weight: 600; color: #0b3d2e; font-size: 15px;"><?= $invoiceDate->format('M j, Y') ?></div>
                      <div style="font-size: 13px; color: #64748b;"><?= $invoiceDate->format('g:i A') ?></div>
                    </td>
                    <td style="padding: 20px 16px;">
                      <div style="display: flex; align-items: center; gap: 12px;">
                        <div style="width: 36px; height: 36px; background: linear-gradient(135deg, #10b981, #059669); border-radius: 50%; display: flex; align-items: center; justify-content: center; color: white; font-weight: 700; font-size: 13px;">
                          <?= strtoupper(substr($earning['first_name'], 0, 1)) . strtoupper(substr($earning['last_name'], 0, 1)) ?>
                        </div>
                        <div style="font-weight: 600; color: #0b3d2e; font-size: 15px;">
                          <?= htmlspecialchars($earning['first_name'] . ' ' . $earning['last_name']) ?>
                        </div>
                      </div>
                    </td>
                    <td style="padding: 20px 16px;">
                      <div style="color: #374151; font-weight: 500;"><?= $earning['duration_minutes'] ?> minutes</div>
                      <div style="font-size: 13px; color: #64748b;">
                        <?= (new DateTime($earning['starts_at']))->format('M j @ g:i A') ?>
                      </div>
                    </td>
                    <td style="padding: 20px 16px;">
                      <div style="font-size: 18px; font-weight: 700; color: #0b3d2e;">$<?= number_format($earning['total_amount'], 2) ?></div>
                    </td>
                    <td style="padding: 20px 16px;">
                      <span style="<?= $statusStyles[$earning['payment_status']] ?? 'background: #f3f4f6; color: #374151;' ?> padding: 6px 14px; border-radius: 12px; font-size: 12px; font-weight: 700; text-transform: uppercase; display: inline-block;">
                        <?= ucfirst($earning['payment_status']) ?>
                      </span>
                    </td>
                  </tr>
                <?php endforeach; ?>
              </tbody>
            </table>
          </div>
        <?php endif; ?>
      </div>

      <!-- Info Card -->
      <div style="background: linear-gradient(135deg, #eff6ff, #dbeafe); padding: 24px; border-radius: 16px; border: 2px solid #bfdbfe;">
        <div style="display: flex; align-items: start; gap: 16px;">
          <div style="width: 48px; height: 48px; background: linear-gradient(135deg, #3b82f6, #2563eb); border-radius: 12px; display: flex; align-items: center; justify-content: center; color: white; flex-shrink: 0;">
            <i class="fas fa-info-circle" style="font-size: 20px;"></i>
          </div>
          <div>
            <h3 style="font-size: 17px; font-weight: 700; color: #1e3a8a; margin: 0 0 12px 0;">About Your Earnings</h3>
            <p style="font-size: 14px; color: #1e40af; line-height: 1.6; margin: 0;">
              Your hourly rate is <strong>$<?= number_format($coach['hourly_rate'] ?? 0, 2) ?></strong>. 
              Earnings are calculated based on session duration and are paid when clients complete their invoice payment. 
              Payouts are processed within 3-5 business days after requesting. You can view detailed breakdowns of each session in the Sessions tab.
            </p>
          </div>
        </div>
      </div>
    </main>
  </div>
</div>

<style>
button:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.2) !important;
}

button:active {
  transform: translateY(0);
}

tr:hover {
  background: #f9fafb !important;
}
</style>

<script>
function requestPayout() {
  const pendingElement = document.getElementById('pending-earnings');
  const pendingText = pendingElement.textContent.replace('$', '').replace(',', '');
  const pendingAmount = parseFloat(pendingText);
  
  if (pendingAmount <= 0) {
    alert('No pending earnings available for payout');
    return;
  }
  
  if (confirm(`Request payout of $${pendingAmount.toFixed(2)}?\n\nPayouts are processed within 3-5 business days.`)) {
    alert('✓ Payout request submitted successfully!\n\nYou will receive an email confirmation shortly.');
    
    // Mock update - in production this would call an API
    const paidElement = document.getElementById('paid-earnings');
    const currentPaid = parseFloat(paidElement.textContent.replace('$', '').replace(',', ''));
    paidElement.textContent = '$' + (currentPaid + pendingAmount).toFixed(2);
    pendingElement.textContent = '$0.00';
  }
}

function exportEarnings() {
  alert('Exporting earnings data...\n\nYour earnings report will be downloaded as a CSV file.');
  // In production, this would generate and download a CSV file
}
</script>

<?php };
include __DIR__ . '/../../partials/layout.php';
?>
