<?php
// /api/towlens/requests.php
declare(strict_types=1);

header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
header('Pragma: no-cache');

session_start();

$ROOT = realpath(__DIR__ . '/..');
if (!$ROOT) { http_response_code(500); echo json_encode(['error' => 'Server path failed']); exit; }

$config = require $ROOT . '/lib/config.php';
require $ROOT . '/lib/db.php';
require $ROOT . '/lib/helpers.php';
require_admin_auth($config);

if (!($pdo instanceof PDO)) { http_response_code(500); echo json_encode(['error' => 'DB unavailable']); exit; }
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$user = $_SESSION['user'] ?? [];
$role = $user['role'] ?? '';
if (!in_array($role, ['admin','org_admin'], true)) {
    http_response_code(403);
    echo json_encode(['error' => 'Forbidden']);
    exit;
}

function jresp($data, int $status = 200): void {
    http_response_code($status);
    echo json_encode($data, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
    exit;
}

// NOTE: assumes `requests` already exists in your TowLens system.
// If you want: add `towlens_template_id` + review fields via migrations as discussed.

$method = $_SERVER['REQUEST_METHOD'] ?? 'GET';

if ($method === 'GET') {
    $id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

    if ($id > 0) {
        $sql = "SELECT * FROM requests WHERE id = ?";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$id]);
        $row = $stmt->fetch(PDO::FETCH_ASSOC);
        if (!$row) jresp(['error' => 'Not found'], 404);
        jresp($row);
    }

    // Filters: status, reg, template, date
    $where  = [];
    $params = [];

    if (!empty($_GET['status'])) {
        $where[] = "LOWER(status) = LOWER(?)";
        $params[] = $_GET['status'];
    }
    if (!empty($_GET['reg'])) {
        $where[] = "reg_mark LIKE ?";
        $params[] = '%' . $_GET['reg'] . '%';
    }
    if (!empty($_GET['template_id'])) {
        $where[] = "towlens_template_id = ?";
        $params[] = (int)$_GET['template_id'];
    }

    $sql = "SELECT * FROM requests";
    if ($where) $sql .= " WHERE " . implode(" AND ", $where);
    $sql .= " ORDER BY id DESC LIMIT 500";

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

if ($method === 'POST') {
    // Create a new TowLens request
    $raw = file_get_contents('php://input');
    $data = json_decode($raw, true) ?? [];

    $reg           = trim($data['reg_mark'] ?? '');
    $customerName  = trim($data['customer_name'] ?? '');
    $customerEmail = trim($data['customer_email'] ?? '');
    $customerPhone = trim($data['customer_phone'] ?? '');
    $templateCode  = trim($data['template_code'] ?? '');
    $notes         = trim($data['notes'] ?? '');
    $source        = trim($data['source'] ?? 'towlens'); // e.g. 'quickhire','pda-lite'

    if ($reg === '' && $customerEmail === '' && $customerPhone === '') {
        jresp(['error' => 'At least one identifier (reg/email/phone) is required'], 400);
    }

    $templateId = null;
    if ($templateCode !== '') {
        $ts = $pdo->prepare("SELECT id FROM towlens_templates WHERE code = ? AND is_active = 1");
        $ts->execute([$templateCode]);
        $templateId = $ts->fetchColumn() ?: null;
    }

    $stmt = $pdo->prepare("
        INSERT INTO requests
          (reg_mark, customer_name, customer_email, customer_phone,
           towlens_template_id, status, notes, source, created_at)
        VALUES
          (?, ?, ?, ?, ?, 'open', ?, ?, NOW())
    ");
    $stmt->execute([
        $reg,
        $customerName,
        $customerEmail,
        $customerPhone,
        $templateId,
        $notes,
        $source
    ]);

    $id = (int)$pdo->lastInsertId();

    // Optional: log in towlens_events
    $ev = $pdo->prepare("
        INSERT INTO towlens_events (request_id, event_type, details, created_by)
        VALUES (?, 'REQUEST_CREATED', ?, ?)
    ");
    $ev->execute([$id, json_encode(['source' => $source]), $user['email'] ?? 'system']);

    jresp(['id' => $id], 201);
}

header('Allow: GET, POST');
jresp(['error' => 'Method not allowed'], 405);
