<?php
$reportActive = 'job_history';
$pageTitle = 'Job History Report';
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');
$status = $_GET['status'] ?? '';
$dtFrom = $dateFrom . ' 00:00:00';
$dtTo = $dateTo . ' 23:59:59';

$where = ["j.created_at BETWEEN ? AND ?"];
$params = [$dtFrom, $dtTo];
if ($status && in_array($status, ['accepted','in_progress','completed','cancelled'])) {
  $where[] = "j.status=?";
  $params[] = $status;
}

$sql = "SELECT j.*, v.vendor_code, v.name vendor_name, l.title lead_title, l.location, l.time_slot, l.lead_price, l.customer_name, l.customer_phone, c.name category_name
        FROM jobs j
        JOIN vendors v ON v.id=j.vendor_id
        JOIN leads l ON l.id=j.lead_id
        LEFT JOIN categories c ON c.id=l.category_id
        WHERE " . implode(" AND ", $where) . "
        ORDER BY j.created_at DESC";
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$jobs = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Summary
$totalJobs = count($jobs);
$totalRevenue = 0; $totalCommission = 0; $completedCount = 0;
foreach ($jobs as $j) {
  if ($j['status']==='completed') {
    $totalRevenue += (int)$j['earning_amount'];
    $totalCommission += (int)round((int)$j['lead_price']*0.2);
    $completedCount++;
  }
}
?>
<div class="page-header">
  <h1>Job History Report</h1>
  <p class="subtitle">Complete job history with timeline</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"><label class="form-label">Status</label><select name="status" class="form-select"><option value="">All</option><option value="accepted" <?php echo $status==='accepted'?'selected':''; ?>>Pending</option><option value="in_progress" <?php echo $status==='in_progress'?'selected':''; ?>>In Progress</option><option value="completed" <?php echo $status==='completed'?'selected':''; ?>>Completed</option><option value="cancelled" <?php echo $status==='cancelled'?'selected':''; ?>>Cancelled</option></select></div>
    <div class="col-md-2"><button type="submit" class="btn btn-dark">Apply</button></div>
  </form>
</div>

<div class="report-summary">
  <div class="summary-item"><div class="label">Total Jobs</div><div class="value"><?php echo $totalJobs; ?></div></div>
  <div class="summary-item"><div class="label">Completed</div><div class="value text-success"><?php echo $completedCount; ?></div></div>
  <div class="summary-item"><div class="label">Vendor Earnings</div><div class="value">₹<?php echo number_format($totalRevenue); ?></div></div>
  <div class="summary-item"><div class="label">Platform Commission</div><div class="value text-warning">₹<?php echo number_format($totalCommission); ?></div></div>
</div>

<div class="card">
  <div class="card-body p-0">
    <div class="table-responsive">
      <table class="table mb-0">
        <thead><tr><th>ID</th><th>Vendor</th><th>Lead</th><th>Customer</th><th>Category</th><th>Status</th><th>Lead Price</th><th>Vendor 80%</th><th>Commission 20%</th><th>Created</th><th>Started</th><th>Completed</th></tr></thead>
        <tbody>
          <?php foreach ($jobs as $j): ?>
          <tr>
            <td>#<?php echo $j['id']; ?></td>
            <td><?php echo htmlspecialchars($j['vendor_code']); ?></td>
            <td><?php echo htmlspecialchars($j['lead_title']); ?></td>
            <td><?php echo htmlspecialchars($j['customer_name']); ?></td>
            <td><?php echo htmlspecialchars($j['category_name'] ?? '-'); ?></td>
            <td><span class="badge bg-<?php echo $j['status']==='completed'?'success':($j['status']==='in_progress'?'primary':'warning'); ?>"><?php echo $j['status']; ?></span></td>
            <td>₹<?php echo number_format($j['lead_price']); ?></td>
            <td>₹<?php echo number_format($j['earning_amount']); ?></td>
            <td class="text-warning">₹<?php echo number_format(round($j['lead_price']*0.2)); ?></td>
            <td class="small"><?php echo date('M d, H:i', strtotime($j['created_at'])); ?></td>
            <td class="small"><?php echo $j['started_at'] ? date('M d, H:i', strtotime($j['started_at'])) : '-'; ?></td>
            <td class="small"><?php echo $j['completed_at'] ? date('M d, H:i', strtotime($j['completed_at'])) : '-'; ?></td>
          </tr>
          <?php endforeach; ?>
          <?php if (empty($jobs)): ?><tr><td colspan="12" class="text-muted">No jobs</td></tr><?php endif; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>
<?php require_once __DIR__ . '/../partials/bottom.php'; ?>
