<?php
$active = 'jobs';
$pageTitle = 'Jobs';
require_once __DIR__ . '/partials/top.php';
$pdo = db();

$view = $_GET['view'] ?? 'all';  // all, pending, ongoing, completed
$status = $_GET['status'] ?? '';
$vendor_id = (int)($_GET['vendor_id'] ?? 0);

$where = [];
$params = [];

if ($view === 'pending') {
  $where[] = "j.status = 'accepted'";
} elseif ($view === 'ongoing') {
  $where[] = "j.status IN ('accepted','in_progress')";
} elseif ($view === 'in_progress') {
  $where[] = "j.status = 'in_progress'";
} elseif ($view === 'completed') {
  $where[] = "j.status = 'completed'";
} elseif ($view === 'cancelled') {
  $where[] = "j.status = 'cancelled'";
}

if ($status !== '') {
  $where[] = "j.status=?";
  $params[] = $status;
}
if ($vendor_id) {
  $where[] = "j.vendor_id=?";
  $params[] = $vendor_id;
}

$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
        FROM jobs j
        JOIN vendors v ON v.id=j.vendor_id
        JOIN leads l ON l.id=j.lead_id";
if ($where) $sql .= " WHERE " . implode(" AND ", $where);
$sql .= " ORDER BY j.created_at DESC";

$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$jobs = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Counts for tabs
$counts = [
  'all' => (int)$pdo->query("SELECT COUNT(*) FROM jobs")->fetchColumn(),
  'pending' => (int)$pdo->query("SELECT COUNT(*) FROM jobs WHERE status='accepted'")->fetchColumn(),
  'in_progress' => (int)$pdo->query("SELECT COUNT(*) FROM jobs WHERE status='in_progress'")->fetchColumn(),
  'ongoing' => (int)$pdo->query("SELECT COUNT(*) FROM jobs WHERE status IN ('accepted','in_progress')")->fetchColumn(),
  'completed' => (int)$pdo->query("SELECT COUNT(*) FROM jobs WHERE status='completed'")->fetchColumn(),
  'cancelled' => (int)$pdo->query("SELECT COUNT(*) FROM jobs WHERE status='cancelled'")->fetchColumn(),
];

function statusBadge($s) {
  $map = ['accepted'=>'warning','in_progress'=>'primary','completed'=>'success','cancelled'=>'secondary'];
  $labels = ['accepted'=>'Pending','in_progress'=>'In Progress','completed'=>'Completed','cancelled'=>'Cancelled'];
  $c = $map[$s] ?? 'secondary';
  $l = $labels[$s] ?? $s;
  return "<span class='badge bg-$c'>$l</span>";
}
?>
<div class="page-header">
  <h1>Jobs</h1>
  <p class="subtitle">Monitor job lifecycle — Pending → In Progress → Completed</p>
</div>

<ul class="nav nav-tabs mb-4">
  <li class="nav-item"><a class="nav-link <?php echo $view==='all'?'active':''; ?>" href="jobs.php?view=all">All (<?php echo $counts['all']; ?>)</a></li>
  <li class="nav-item"><a class="nav-link <?php echo $view==='pending'?'active':''; ?>" href="jobs.php?view=pending">Pending (<?php echo $counts['pending']; ?>)</a></li>
  <li class="nav-item"><a class="nav-link <?php echo $view==='in_progress'?'active':''; ?>" href="jobs.php?view=in_progress">In Progress (<?php echo $counts['in_progress']; ?>)</a></li>
  <li class="nav-item"><a class="nav-link <?php echo $view==='ongoing'?'active':''; ?>" href="jobs.php?view=ongoing">Ongoing (<?php echo $counts['ongoing']; ?>)</a></li>
  <li class="nav-item"><a class="nav-link <?php echo $view==='completed'?'active':''; ?>" href="jobs.php?view=completed">Completed (<?php echo $counts['completed']; ?>)</a></li>
  <li class="nav-item"><a class="nav-link <?php echo $view==='cancelled'?'active':''; ?>" href="jobs.php?view=cancelled">Cancelled (<?php echo $counts['cancelled']; ?>)</a></li>
</ul>

<form class="row g-2 mb-3">
  <input type="hidden" name="view" value="<?php echo htmlspecialchars($view); ?>">
  <div class="col-md-2"><input class="form-control" name="vendor_id" value="<?php echo $vendor_id ?: ''; ?>" placeholder="Vendor ID"></div>
  <div class="col-md-2"><button class="btn btn-dark" type="submit">Filter</button></div>
</form>

<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 / Customer</th>
            <th>Time Slot</th>
            <th>Status</th>
            <th>Payment</th>
            <th>Lead Price</th>
            <th>Vendor Earning (80%)</th>
            <th>Commission (20%)</th>
            <th>Photos</th>
            <th>Timeline</th>
          </tr>
        </thead>
        <tbody>
          <?php foreach ($jobs as $j): 
            $commission = (int)round((int)$j['lead_price'] * 0.2);
          ?>
          <tr>
            <td class="fw-semibold"><a href="job_view.php?id=<?php echo $j['id']; ?>">#<?php echo $j['id']; ?></a></td>
            <td><strong><?php echo htmlspecialchars($j['vendor_code']); ?></strong><div class="small text-muted"><?php echo htmlspecialchars($j['vendor_name']); ?></div></td>
            <td><?php echo htmlspecialchars($j['lead_title']); ?><div class="small text-muted"><?php echo htmlspecialchars($j['customer_name']); ?> • <?php echo htmlspecialchars($j['location']); ?></div></td>
            <td><?php echo htmlspecialchars($j['time_slot']); ?></td>
            <td><?php echo statusBadge($j['status']); ?></td>
            <td><span class="badge bg-<?php echo ($j['payment_mode']??'online')==='cod'?'warning':'primary'; ?>"><?php echo $j['payment_mode'] ?? 'online'; ?></span></td>
            <td>₹<?php echo number_format($j['lead_price']); ?></td>
            <td class="text-success">₹<?php echo number_format($j['earning_amount']); ?></td>
            <td class="text-warning">₹<?php echo number_format($commission); ?></td>
            <td class="small">
              <?php if ($j['before_photo_path']): ?><a target="_blank" href="../<?php echo htmlspecialchars($j['before_photo_path']); ?>">Before</a><?php else: ?><span class="text-muted">-</span><?php endif; ?>
              / <?php if ($j['after_photo_path']): ?><a target="_blank" href="../<?php echo htmlspecialchars($j['after_photo_path']); ?>">After</a><?php else: ?><span class="text-muted">-</span><?php endif; ?>
            </td>
            <td class="small text-muted">
              <div>Created: <?php echo date('M d H:i', strtotime($j['created_at'])); ?></div>
              <?php if ($j['started_at']): ?><div>Started: <?php echo date('M d H:i', strtotime($j['started_at'])); ?></div><?php endif; ?>
              <?php if ($j['completed_at']): ?><div>Done: <?php echo date('M d H:i', strtotime($j['completed_at'])); ?></div><?php endif; ?>
            </td>
          </tr>
          <?php endforeach; ?>
          <?php if (empty($jobs)): ?>
          <tr><td colspan="11" class="text-muted text-center py-4">No jobs found.</td></tr>
          <?php endif; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>

<div class="mt-3">
  <a href="reports/job_history_report.php" class="btn btn-outline-dark">📋 Full Job History Report</a>
</div>
<?php require_once __DIR__ . '/partials/bottom.php'; ?>
