<?php
require_once __DIR__ . '/../app/bootstrap.php';
use App\Core\Auth; use App\Core\PosService; use App\Core\Database; use App\Core\Response; use App\Core\Security;
PosService::requireAccess('public/login.php');
if (!PosService::can('pos.sell')) Response::json(['ok'=>false,'message'=>'No POS sale permission.'],403);
$q = mb_substr(trim((string)($_GET['q'] ?? '')),0,120);
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    $rows = $q === '' ? [] : Database::fetchAll('SELECT id,name,email,phone FROM users WHERE role IN ("customer","affiliate") AND status="active" AND (name LIKE ? OR phone LIKE ? OR email LIKE ?) ORDER BY id DESC LIMIT 15', ['%'.$q.'%','%'.$q.'%','%'.$q.'%']);
    Response::json(['ok'=>true,'customers'=>$rows]);
}
if ($_SERVER['REQUEST_METHOD'] !== 'POST' || !verify_csrf()) Response::json(['ok'=>false,'message'=>'Invalid request.'],419);
if (!Security::rateLimit('pos-customer:'.Auth::id(),30,3600)) Response::json(['ok'=>false,'message'=>'Too many customer records were created. Try again later.'],429);
$name = mb_substr(trim((string)($_POST['name'] ?? '')),0,150);
$phone = mb_substr(trim((string)($_POST['phone'] ?? '')),0,50);
if ($name === '') Response::json(['ok'=>false,'message'=>'Customer name is required.'],422);
if ($phone !== '' && !preg_match('/^[0-9+() -]{6,30}$/',$phone)) Response::json(['ok'=>false,'message'=>'Enter a valid phone number.'],422);
if ($phone !== '') {
    $existing = Database::safeFetchOne('SELECT id,name,email,phone FROM users WHERE phone=? AND status<>"deleted" ORDER BY id DESC LIMIT 1',[$phone]);
    if ($existing) Response::json(['ok'=>true,'customer_id'=>(int)$existing['id'],'customer'=>$existing,'message'=>'Existing customer selected.']);
}
Database::execute('INSERT INTO users (role,name,phone,status,created_at,updated_at) VALUES ("customer",?,? ,"active",NOW(),NOW())', [$name,$phone ?: null]);
$id=Database::lastInsertId();
Security::logActivity(Auth::id(),'pos_customer_created',['customer_id'=>$id]);
Response::json(['ok'=>true,'customer_id'=>$id,'message'=>'Customer saved.']);
