<?php
require 'db.php';
header('Content-Type: application/json; charset=utf-8');

$id = intval($_GET['id'] ?? 0);
$search = $_GET['search'] ?? '';

if ($id) {
    $stmt = $conn->prepare("SELECT id,name,phone,email,address,created_at FROM customers WHERE id = ? LIMIT 1");
    $stmt->bind_param('i',$id);
    $stmt->execute();
    $res = $stmt->get_result()->fetch_assoc();
    echo json_encode(['status'=>'ok','customer'=>$res]);
    exit;
}

if ($search) {
    $s = "%{$search}%";
    $stmt = $conn->prepare("SELECT id,name,phone,email FROM customers WHERE name LIKE ? OR phone LIKE ? LIMIT 50");
    $stmt->bind_param('ss',$s,$s);
    $stmt->execute();
    $rows = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    echo json_encode(['status'=>'ok','results'=>$rows]);
    exit;
}

// default: list (paginated)
$page = max(1,intval($_GET['page'] ?? 1));
$pageSize = 50;
$offset = ($page-1)*$pageSize;
$stmt = $conn->prepare("SELECT id,name,phone,email FROM customers ORDER BY id DESC LIMIT ?,?");
$stmt->bind_param('ii',$offset,$pageSize);
$stmt->execute();
$rows = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
echo json_encode(['status'=>'ok','page'=>$page,'results'=>$rows]);
exit;
