<?php
require_auth();
$method = $_SERVER['REQUEST_METHOD']; $d = input(); $id=(int)($d['id']??0);
if ($method === 'GET') {
    require_permission('tickets.view');
    $where='1=1'; $params=[];
    if (!empty($d['status'])) { $where.=' AND t.status=?'; $params[]=$d['status']; }
    if (!empty($d['property_id'])) { $where.=' AND t.property_id=?'; $params[]=(int)$d['property_id']; }
    $s = db()->prepare('SELECT t.*, p.name AS property_name, u.name AS assignee_name FROM tickets t JOIN properties p ON p.id=t.property_id LEFT JOIN users u ON u.id=t.assigned_to WHERE '.$where.' ORDER BY FIELD(t.priority,"urgent","high","medium","low"), t.created_at DESC LIMIT 500');
    $s->execute($params);
    json_ok($s->fetchAll());
}
csrf_check();
if ($method==='POST') {
    require_permission('tickets.manage');
    $err = v_required($d, ['property_id','title']);
    if ($err) json_error('Validation failed',422,$err);
    db()->prepare('INSERT INTO tickets (property_id,title,description,category,priority,status,assigned_to,created_by,due_date) VALUES (?,?,?,?,?,?,?,?,?)')
        ->execute([(int)$d['property_id'], v_str($d,'title',190), (string)($d['description']??''), v_enum($d['category']??'maintenance', ['maintenance','cleaning','inspection','emergency','other'], 'category', 'maintenance'), v_enum($d['priority']??'medium', ['low','medium','high','urgent'], 'priority', 'medium'), v_enum($d['status']??'open', ['open','assigned','in_progress','completed','cancelled'], 'status', 'open'), !empty($d['assigned_to'])?(int)$d['assigned_to']:null, current_user()['id']??null, !empty($d['due_date']) ? v_date($d['due_date'], 'due_date') : null]);
    $nid = db()->lastInsertId();
    audit('ticket.create','ticket',$nid);
    json_ok(['id'=>$nid], 'Ticket created');
}
if ($method==='PUT') {
    require_permission('tickets.manage');
    if (!$id) json_error('id required',422);
    $allowed=['title','description','category','priority','status','assigned_to','due_date'];
    $fields=[]; $vals=[];
    foreach ($allowed as $f) if (array_key_exists($f,$d)) { if ($f==='category') $d[$f]=v_enum($d[$f], ['maintenance','cleaning','inspection','emergency','other'], 'category'); if ($f==='priority') $d[$f]=v_enum($d[$f], ['low','medium','high','urgent'], 'priority'); if ($f==='status') $d[$f]=v_enum($d[$f], ['open','assigned','in_progress','completed','cancelled'], 'status'); if ($f==='due_date' && $d[$f]) $d[$f]=v_date($d[$f], 'due_date'); $fields[]="$f=?"; $vals[]=$d[$f]; }
    if (!$fields) json_error('Nothing to update',422);
    if (($d['status']??'')==='completed') { $fields[]='completed_at=NOW()'; }
    $vals[]=$id;
    db()->prepare('UPDATE tickets SET '.implode(',',$fields).' WHERE id=?')->execute($vals);
    audit('ticket.update','ticket',$id);
    json_ok([],'Updated');
}
if ($method==='DELETE') {
    require_permission('tickets.manage');
    if (!$id) json_error('id required',422);
    db()->prepare('UPDATE tickets SET status="cancelled" WHERE id=?')->execute([$id]);
    audit('ticket.cancel','ticket',$id);
    json_ok([],'Deleted');
}
json_error('Method not allowed',405);
