<?php
$reportActive = 'business';
$pageTitle = 'Business Eagle View';
require_once __DIR__ . '/../partials/top.php';

$pdo = db();
$dateFrom = $_GET['date_from'] ?? date('Y-m-d', strtotime('-30 days'));
$dateTo = $_GET['date_to'] ?? date('Y-m-d');
$dtFrom = $dateFrom . ' 00:00:00';
$dtTo = $dateTo . ' 23:59:59';

// Flow: Users (customers) → Leads → Jobs → Vendors
$stmt = $pdo->prepare("SELECT COUNT(*) FROM leads WHERE created_at BETWEEN ? AND ?");
$stmt->execute([$dtFrom, $dtTo]);
$leadsCount = (int)$stmt->fetchColumn();

$stmt = $pdo->prepare("SELECT COUNT(*) FROM leads WHERE is_available=0 AND created_at BETWEEN ? AND ?");
$stmt->execute([$dtFrom, $dtTo]);
$leadsConverted = (int)$stmt->fetchColumn();

$stmt = $pdo->prepare("SELECT COUNT(*) FROM jobs WHERE created_at BETWEEN ? AND ?");
$stmt->execute([$dtFrom, $dtTo]);
$jobsCount = (int)$stmt->fetchColumn();

$stmt = $pdo->prepare("SELECT COUNT(*) FROM jobs WHERE status='completed' AND completed_at BETWEEN ? AND ?");
$stmt->execute([$dtFrom, $dtTo]);
$jobsCompleted = (int)$stmt->fetchColumn();

$stmt = $pdo->prepare("SELECT COUNT(DISTINCT customer_phone) FROM leads WHERE created_at BETWEEN ? AND ? AND customer_phone IS NOT NULL AND customer_phone != ''");
$stmt->execute([$dtFrom, $dtTo]);
$uniqueCustomers = (int)$stmt->fetchColumn();

$stmt = $pdo->prepare("SELECT COUNT(DISTINCT vendor_id) FROM jobs WHERE created_at BETWEEN ? AND ?");
$stmt->execute([$dtFrom, $dtTo]);
$activeVendors = (int)$stmt->fetchColumn();

$stmt = $pdo->prepare("SELECT COALESCE(SUM(earning_amount),0) FROM jobs WHERE status='completed' AND completed_at BETWEEN ? AND ?");
$stmt->execute([$dtFrom, $dtTo]);
$totalRevenue = (int)$stmt->fetchColumn();

$stmt = $pdo->prepare("SELECT COALESCE(SUM(amount),0) FROM wallet_transactions WHERE type='debit' AND ref_type='lead' AND created_at BETWEEN ? AND ?");
$stmt->execute([$dtFrom, $dtTo]);
$platformCommission = (int)$stmt->fetchColumn();

// User orders (app)
$appUsersTotal = 0;
$userOrdersCount = 0;
$userOrdersRevenue = 0;
try {
  $stmt = $pdo->prepare("SELECT COUNT(*) FROM users WHERE created_at BETWEEN ? AND ?");
  $stmt->execute([$dtFrom, $dtTo]);
  $appUsersTotal = (int)$stmt->fetchColumn();
  $stmt = $pdo->prepare("SELECT COUNT(*), COALESCE(SUM(total_amount),0) FROM user_orders WHERE created_at BETWEEN ? AND ? AND payment_status='paid'");
  $stmt->execute([$dtFrom, $dtTo]);
  $r = $stmt->fetch();
  $userOrdersCount = (int)$r[0];
  $userOrdersRevenue = (int)$r[1];
} catch (Exception $e) {}

// Top flow data
$stmt = $pdo->prepare("
  SELECT c.name cat, COUNT(l.id) leads, COUNT(j.id) jobs
  FROM leads l
  LEFT JOIN categories c ON c.id=l.category_id
  LEFT JOIN jobs j ON j.lead_id=l.id AND j.status='completed'
  WHERE l.created_at BETWEEN ? AND ?
  GROUP BY l.category_id, c.name ORDER BY leads DESC
");
$stmt->execute([$dtFrom, $dtTo]);
$flowByCategory = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<div class="page-header">
  <h1>Business Eagle View</h1>
  <p class="subtitle">Leads → Jobs → Vendors → Users — Complete alignment</p>
</div>

<div class="report-filters">
  <form method="get" class="row g-3 align-items-end">
    <div class="col-md-2"><label class="form-label">From</label><input type="date" name="date_from" class="form-control" value="<?php echo htmlspecialchars($dateFrom); ?>"></div>
    <div class="col-md-2"><label class="form-label">To</label><input type="date" name="date_to" class="form-control" value="<?php echo htmlspecialchars($dateTo); ?>"></div>
    <div class="col-md-2"><button type="submit" class="btn btn-dark">Apply</button></div>
  </form>
</div>

<!-- Flow Diagram -->
<div class="card mb-4 p-4">
  <div class="text-center mb-4">
    <h5 class="fw-bold">Business Flow</h5>
    <p class="text-muted small">Users book → Leads created → Vendors pick → Jobs completed</p>
  </div>
  <div class="row g-3 align-items-center justify-content-center">
    <div class="col-md-3">
      <div class="card border-primary p-4 text-center">
        <div class="fs-2 fw-bold text-primary"><?php echo $uniqueCustomers; ?></div>
        <div class="text-muted">Users / Customers</div>
      </div>
    </div>
    <div class="col-md-1 text-center"><span class="fs-4">→</span></div>
    <div class="col-md-3">
      <div class="card border-info p-4 text-center">
        <div class="fs-2 fw-bold text-info"><?php echo $leadsCount; ?></div>
        <div class="text-muted">Leads</div>
        <div class="small"><?php echo $leadsConverted; ?> converted</div>
      </div>
    </div>
    <div class="col-md-1 text-center"><span class="fs-4">→</span></div>
    <div class="col-md-3">
      <div class="card border-warning p-4 text-center">
        <div class="fs-2 fw-bold text-warning"><?php echo $jobsCount; ?></div>
        <div class="text-muted">Jobs</div>
        <div class="small"><?php echo $jobsCompleted; ?> completed</div>
      </div>
    </div>
    <div class="col-md-1 text-center"><span class="fs-4">→</span></div>
    <div class="col-md-3">
      <div class="card border-success p-4 text-center">
        <div class="fs-2 fw-bold text-success"><?php echo $activeVendors; ?></div>
        <div class="text-muted">Active Vendors</div>
      </div>
    </div>
  </div>
</div>

<div class="row g-4 mb-4">
  <div class="col-md-4">
    <div class="card p-4">
      <div class="d-flex justify-content-between align-items-center">
        <div>
          <div class="text-muted small">Total Revenue (Vendor 80%)</div>
          <div class="fs-3 fw-bold text-success">₹<?php echo number_format($totalRevenue); ?></div>
        </div>
      </div>
    </div>
  </div>
  <?php if (isset($userOrdersRevenue) && $userOrdersRevenue > 0): ?>
  <div class="col-md-4">
    <div class="card p-4">
      <div class="d-flex justify-content-between align-items-center">
        <div>
          <div class="text-muted small">User Orders Revenue (App)</div>
          <div class="fs-3 fw-bold text-info">₹<?php echo number_format($userOrdersRevenue); ?></div>
          <div class="small"><?php echo $userOrdersCount; ?> paid orders</div>
        </div>
      </div>
    </div>
  </div>
  <?php endif; ?>
  <div class="col-md-4">
    <div class="card p-4">
      <div class="d-flex justify-content-between align-items-center">
        <div>
          <div class="text-muted small">Platform Commission (20%)</div>
          <div class="fs-3 fw-bold text-warning">₹<?php echo number_format($platformCommission); ?></div>
        </div>
      </div>
    </div>
  </div>
  <div class="col-md-4">
    <div class="card p-4">
      <div class="d-flex justify-content-between align-items-center">
        <div>
          <div class="text-muted small">Conversion Rate</div>
          <div class="fs-3 fw-bold"><?php echo $leadsCount > 0 ? round(($leadsConverted/$leadsCount)*100, 1) : 0; ?>%</div>
        </div>
      </div>
    </div>
  </div>
</div>

<div class="row g-4">
  <div class="col-lg-8">
    <div class="card">
      <div class="card-header">Leads → Jobs by Category</div>
      <div class="card-body">
        <div class="chart-container"><canvas id="flowChart"></canvas></div>
      </div>
    </div>
  </div>
  <div class="col-lg-4">
    <div class="card">
      <div class="card-header">Quick Stats</div>
      <div class="card-body">
        <table class="table table-sm">
          <tr><td>Unique Customers</td><td class="text-end fw-bold"><?php echo $uniqueCustomers; ?></td></tr>
          <tr><td>Total Leads</td><td class="text-end fw-bold"><?php echo $leadsCount; ?></td></tr>
          <tr><td>Leads Converted</td><td class="text-end fw-bold text-success"><?php echo $leadsConverted; ?></td></tr>
          <tr><td>Jobs Created</td><td class="text-end fw-bold"><?php echo $jobsCount; ?></td></tr>
          <tr><td>Jobs Completed</td><td class="text-end fw-bold text-success"><?php echo $jobsCompleted; ?></td></tr>
          <tr><td>Active Vendors</td><td class="text-end fw-bold"><?php echo $activeVendors; ?></td></tr>
          <?php if (isset($appUsersTotal) || isset($userOrdersCount)): ?>
          <tr><td>New App Users</td><td class="text-end fw-bold"><?php echo $appUsersTotal ?? 0; ?></td></tr>
          <tr><td>User Orders (Paid)</td><td class="text-end fw-bold"><?php echo $userOrdersCount ?? 0; ?></td></tr>
          <?php endif; ?>
        </table>
      </div>
    </div>
  </div>
</div>

<script>
const flowData = <?php echo json_encode($flowByCategory); ?>;
new Chart(document.getElementById('flowChart'), {
  type: 'bar',
  data: {
    labels: flowData.map(r=>r.cat||'Uncategorized'),
    datasets: [
      { label: 'Leads', data: flowData.map(r=>r.leads), backgroundColor: 'rgba(59,130,246,0.7)', borderRadius: 4 },
      { label: 'Jobs Done', data: flowData.map(r=>r.jobs), backgroundColor: 'rgba(16,185,129,0.7)', borderRadius: 4 }
    ]
  },
  options: { responsive: true, maintainAspectRatio: false, scales: { x: { stacked: false }, y: { beginAtZero: true } } }
});
</script>
<?php require_once __DIR__ . '/../partials/bottom.php'; ?>
