
<?php
require_once __DIR__ . '/api_auth.php';
$db = (new Database())->getConnection();
ensureUnifiedTicketWorkflow($db);
api_require_client($db);
$action = strtolower($_GET['action'] ?? 'list');
$method = $_SERVER['REQUEST_METHOD'];

$allowed = ['request_number','er_ticket_id','full_name','phone_number','secondary_phone','customer_email','service_address','service_address_2','region','state','zip_code','issue_description','special_request','job_status_id','urgency_level_id','source_system','origin_type','ticket_source','sync_status'];

try {
    if ($action === 'list' && $method === 'GET') {
        $source = $_GET['source_system'] ?? 'all';
        $where = [];
        $params = [];
        if ($source !== 'all') { $where[] = 'source_system = :source'; $params[':source'] = $source; }
        if (!empty($_GET['updated_after'])) { $where[] = 'COALESCE(last_updated_at, requested_at) >= :updated_after'; $params[':updated_after'] = $_GET['updated_after']; }
        $whereSql = $where ? ('WHERE '.implode(' AND ', $where)) : '';
        $limit = min(200, max(1, (int)($_GET['limit'] ?? 100)));
        $stmt = $db->prepare("SELECT id, request_number, er_ticket_id, source_system, origin_type, ticket_source, sync_status, full_name, phone_number, customer_email, service_address, region, state, zip_code, issue_description, job_status_id, urgency_level_id, requested_at, last_updated_at FROM service_requests $whereSql ORDER BY COALESCE(last_updated_at, requested_at) DESC LIMIT :limit");
        foreach ($params as $k=>$v) $stmt->bindValue($k,$v);
        $stmt->bindValue(':limit',$limit,PDO::PARAM_INT);
        $stmt->execute();
        api_json(['success'=>true,'tickets'=>$stmt->fetchAll(PDO::FETCH_ASSOC)]);
    }

    if ($action === 'create' && $method === 'POST') {
        $b = api_body();
        $requestNumber = trim((string)($b['request_number'] ?? $b['er_ticket_id'] ?? 'ER-'.date('Ymd-His')));
        $stmt = $db->prepare("INSERT INTO service_requests (request_number, er_ticket_id, ticket_source, source_system, origin_type, sync_status, full_name, phone_number, secondary_phone, customer_email, service_address, service_address_2, region, state, zip_code, issue_description, special_request, job_status_id, urgency_level_id, is_serviceable, requested_at, last_updated_at, last_synced_at) VALUES (:request_number,:er_ticket_id,'er_typescript','typescript_er',:origin_type,'er_imported',:full_name,:phone_number,:secondary_phone,:customer_email,:service_address,:service_address_2,:region,:state,:zip_code,:issue_description,:special_request,:job_status_id,:urgency_level_id,1,NOW(),NOW(),NOW())");
        $stmt->execute([
            ':request_number'=>$requestNumber,
            ':er_ticket_id'=>$b['er_ticket_id'] ?? null,
            ':origin_type'=>$b['origin_type'] ?? 'ER Ticket',
            ':full_name'=>$b['full_name'] ?? 'ER Customer',
            ':phone_number'=>$b['phone_number'] ?? '',
            ':secondary_phone'=>$b['secondary_phone'] ?? null,
            ':customer_email'=>$b['customer_email'] ?? null,
            ':service_address'=>$b['service_address'] ?? 'Address from ER',
            ':service_address_2'=>$b['service_address_2'] ?? null,
            ':region'=>$b['region'] ?? null,
            ':state'=>$b['state'] ?? null,
            ':zip_code'=>$b['zip_code'] ?? '00000',
            ':issue_description'=>$b['issue_description'] ?? null,
            ':special_request'=>$b['special_request'] ?? null,
            ':job_status_id'=>(int)($b['job_status_id'] ?? $b['status_id'] ?? 1),
            ':urgency_level_id'=>(int)($b['urgency_level_id'] ?? 1),
        ]);
        api_json(['success'=>true,'id'=>(int)$db->lastInsertId(),'request_number'=>$requestNumber],201);
    }

    if ($action === 'update' && in_array($method, ['PATCH','POST'], true)) {
        $id = (int)($_GET['id'] ?? 0);
        if ($id <= 0) api_json(['success'=>false,'message'=>'Missing id'],400);
        $b = api_body();
        $sets = [];
        $params = [':id'=>$id];
        foreach ($allowed as $field) {
            if (array_key_exists($field, $b)) { $sets[] = "$field = :$field"; $params[":$field"] = $b[$field]; }
        }
        if (!$sets) api_json(['success'=>false,'message'=>'No allowed fields to update'],400);
        $sets[] = "source_system = COALESCE(source_system, 'typescript_er')";
        $sets[] = "last_updated_at = NOW()";
        $sets[] = "last_synced_at = NOW()";
        $sql = 'UPDATE service_requests SET '.implode(', ', $sets).' WHERE id = :id';
        $stmt = $db->prepare($sql);
        $stmt->execute($params);
        api_json(['success'=>true,'updated'=>$stmt->rowCount()]);
    }

    if ($action === 'delete' && $method === 'DELETE') {
        $id = (int)($_GET['id'] ?? 0);
        if ($id <= 0) api_json(['success'=>false,'message'=>'Missing id'],400);
        $stmt = $db->prepare('DELETE FROM service_requests WHERE id = :id');
        $stmt->execute([':id'=>$id]);
        api_json(['success'=>true,'deleted'=>$stmt->rowCount()]);
    }

    api_json(['success'=>false,'message'=>'Unsupported action/method'],405);
} catch (Throwable $e) {
    api_json(['success'=>false,'message'=>$e->getMessage()],500);
}
