<?php
// POST /api/clients/get.php
// Body: token, id
require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/../config/auth.php';

$user = requireAuth();
$db   = getDB();
$id   = (int)post('id', 0);

if (!$id) apiError('Client ID required.', 422);

$stmt = $db->prepare("SELECT c.*, u.full_name AS created_by_name FROM clients c LEFT JOIN users u ON u.id = c.created_by WHERE c.id = ?");
$stmt->execute([$id]);
$client = $stmt->fetch();

if (!$client) apiError('Client not found.', 404);

// Contacts
$contacts = $db->prepare("SELECT * FROM client_contacts WHERE client_id = ? ORDER BY is_primary DESC, full_name ASC");
$contacts->execute([$id]);
$client['contacts'] = $contacts->fetchAll();

// Addresses
$addresses = $db->prepare("SELECT * FROM client_addresses WHERE client_id = ?");
$addresses->execute([$id]);
$client['addresses'] = $addresses->fetchAll();

// Notes
$notes = $db->prepare("
    SELECT cn.*, u.full_name AS user_name 
    FROM client_notes cn 
    JOIN users u ON u.id = cn.user_id 
    WHERE cn.client_id = ? 
    ORDER BY cn.created_at DESC
");
$notes->execute([$id]);
$client['notes'] = $notes->fetchAll();

// Projects
$projects = $db->prepare("SELECT id, name, status, priority, target_date FROM projects WHERE client_id = ? ORDER BY created_at DESC");
$projects->execute([$id]);
$client['projects'] = $projects->fetchAll();

// Recent job cards
$jobs = $db->prepare("SELECT id, job_number, title, status, scheduled_date FROM job_cards WHERE client_id = ? ORDER BY created_at DESC LIMIT 5");
$jobs->execute([$id]);
$client['recent_jobs'] = $jobs->fetchAll();

apiSuccess(['client' => $client]);
