<?php
require_auth();
$method = $_SERVER['REQUEST_METHOD'];
$d = input();
$id = (int)($d['id'] ?? 0);

if ($method === 'GET') {
    require_permission('properties.view');
    if ($id) {
        $u = current_user();
        $isAdmin = has_permission('properties.manage') || in_array($u['role_name'] ?? '', ['super_admin', 'admin'], true);
        
        $s = db()->prepare('SELECT * FROM properties WHERE id=? AND deleted_at IS NULL');
        $s->execute([$id]);
        $p = $s->fetch();
        if (!$p) json_error('Not found',404);
        
        // RBAC check for single property
        if (!$isAdmin && $p['manager_id'] !== $u['id']) {
            if (function_exists('hv4_table_exists') && hv4_table_exists('property_assignments')) {
                $chk = db()->prepare('SELECT 1 FROM property_assignments WHERE property_id=? AND user_id=?');
                $chk->execute([$id, $u['id']]);
                if (!$chk->fetchColumn()) json_error('Access denied', 403);
            } else {
                json_error('Access denied', 403);
            }
        }
        
        $imgs = db()->prepare('SELECT * FROM property_images WHERE property_id=? ORDER BY sort_order');
        $imgs->execute([$id]);
        $p['images'] = $imgs->fetchAll();
        json_ok($p);
    }
    
    $u = current_user();
    $isAdmin = has_permission('properties.manage') || in_array($u['role_name'] ?? '', ['super_admin', 'admin'], true);
    $q = '%' . v_str($d,'q',80) . '%';
    
    $where = 'deleted_at IS NULL';
    $params = [];
    
    if (!$isAdmin) {
        if (function_exists('hv4_table_exists') && hv4_table_exists('property_assignments')) {
            $where .= ' AND id IN (SELECT property_id FROM property_assignments WHERE user_id = ?)';
            $params[] = $u['id'];
        } else {
            $where .= ' AND manager_id = ?';
            $params[] = $u['id'];
        }
    }
    
    $where .= ' AND (name LIKE ? OR city LIKE ?)';
    $params[] = $q;
    $params[] = $q;

    $stmt = db()->prepare("SELECT id,name,type,city,country,bedrooms,bathrooms,max_guests,base_price,currency,status,cover_image FROM properties WHERE $where ORDER BY created_at DESC LIMIT 500");
    $stmt->execute($params);
    json_ok($stmt->fetchAll());
}

csrf_check();

if ($method === 'POST') {
    require_permission('properties.manage');
    $errors = v_required($d, ['name']);
    if ($errors) json_error('Validation failed',422,$errors);
    $stmt = db()->prepare('INSERT INTO properties (name,type,address,city,country,bedrooms,bathrooms,max_guests,base_price,cleaning_fee,currency,status,manager_id,description) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)');
    $stmt->execute([
        v_str($d,'name',190),
        v_enum($d['type'] ?? 'apartment', ['apartment','villa','hotel_room','studio','house','other'], 'type', 'apartment'),
        v_str($d,'address',255),
        v_str($d,'city',100),
        v_str($d,'country',100),
        (int)($d['bedrooms'] ?? 1),
        (int)($d['bathrooms'] ?? 1),
        (int)($d['max_guests'] ?? 2),
        (float)($d['base_price'] ?? 0),
        (float)($d['cleaning_fee'] ?? 0),
        substr($d['currency'] ?? 'USD',0,8),
        v_enum($d['status'] ?? 'active', ['active','inactive','maintenance'], 'status', 'active'),
        !empty($d['manager_id']) ? (int)$d['manager_id'] : null,
        (string)($d['description'] ?? ''),
    ]);
    $nid = db()->lastInsertId();
    audit('property.create','property',$nid);
    json_ok(['id'=>$nid], 'Property added');
}

if ($method === 'PUT') {
    require_permission('properties.manage');
    if (!$id) json_error('id required',422);
    $allowed = ['name','type','address','city','country','bedrooms','bathrooms','max_guests','base_price','cleaning_fee','currency','status','manager_id','description','cover_image'];
    $fields=[]; $vals=[];
    foreach ($allowed as $f) if (array_key_exists($f,$d)) { if ($f==='type') $d[$f]=v_enum($d[$f], ['apartment','villa','hotel_room','studio','house','other'], 'type'); if ($f==='status') $d[$f]=v_enum($d[$f], ['active','inactive','maintenance'], 'status'); $fields[]="$f=?"; $vals[]=$d[$f]; }
    if (!$fields) json_error('Nothing to update',422);
    $vals[]=$id;
    db()->prepare('UPDATE properties SET '.implode(',',$fields).' WHERE id=?')->execute($vals);
    audit('property.update','property',$id);
    json_ok([], 'Updated');
}

if ($method === 'DELETE') {
    require_permission('properties.manage');
    if (!$id) json_error('id required',422);
    db()->prepare('UPDATE properties SET deleted_at=NOW(), status="inactive" WHERE id=?')->execute([$id]);
    audit('property.delete','property',$id);
    json_ok([], 'Property removed');
}

json_error('Method not allowed',405);
