<?php
declare(strict_types=1);
require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/../config/zone.php';
require_login();
$pdo = db();
$user = current_user() ?? [];
$role = strtoupper((string)($user['role'] ?? ''));
if (!in_array($role, ['SUPERADMIN','ADMIN','TECHNICIAN'], true)) { http_response_code(403); exit('Forbidden'); }
if ($_SERVER['REQUEST_METHOD'] !== 'POST') { http_response_code(405); exit('Method not allowed'); }
if (!function_exists('verify_csrf_token') || !verify_csrf_token((string)($_POST['csrf_token'] ?? ''))) { http_response_code(400); exit('Sesi keselamatan tamat. Muat semula halaman.'); }
$recordId = max(0, (int)($_POST['patrol_record_id'] ?? 0));
$contractorId = max(0, (int)($_POST['contractor_id'] ?? 0));
if (!$recordId || !$contractorId) { header('Location: patrolling.php?task_error=missing'); exit; }
try {
  $st=$pdo->prepare("SELECT pr.id, r.zone_id FROM patrol_records pr JOIN patrol_locations pl ON pl.id=pr.location_id JOIN routes r ON r.id=pl.route_id WHERE pr.id=? LIMIT 1");
  $st->execute([$recordId]); $rec=$st->fetch(PDO::FETCH_ASSOC);
  if (!$rec) throw new RuntimeException('Rekod patrolling tidak dijumpai.');
  $zoneId = (int)current_user_zone_id();
  if ($role !== 'SUPERADMIN' && $zoneId > 0 && (int)$rec['zone_id'] !== $zoneId) throw new RuntimeException('Tiada akses untuk Zone ini.');
  $st=$pdo->prepare("SELECT id FROM users WHERE id=? AND status='ACTIVE' AND UPPER(role)='CONTRACTOR' LIMIT 1");
  $st->execute([$contractorId]); if (!$st->fetchColumn()) throw new RuntimeException('Pengguna bukan kontraktor aktif.');
  $st=$pdo->prepare("SELECT id FROM patrol_repair_tasks WHERE patrol_record_id=? AND status NOT IN ('REJECTED') LIMIT 1");
  $st->execute([$recordId]); if ($st->fetchColumn()) throw new RuntimeException('Rekod ini sudah mempunyai tugasan.');
  $st=$pdo->prepare("INSERT INTO patrol_repair_tasks (patrol_record_id, assigned_by, contractor_id, status) VALUES (?, ?, ?, 'ASSIGNED')");
  $st->execute([$recordId, (int)($user['id'] ?? 0), $contractorId]);
  header('Location: patrolling.php?task_assigned=1'); exit;
} catch (Throwable $e) { http_response_code(400); echo htmlspecialchars($e->getMessage(), ENT_QUOTES, 'UTF-8'); }
