<?php
require_once __DIR__ . '/../../cors.php'; // Enable CORS for React Native
// GET   /api/customer/profile — get own profile
// PATCH /api/customer/profile — update name / phone / address
require_once __DIR__ . '/../../config/database.php';
require_once __DIR__ . '/../../middleware/auth.php';

$authUser = requireAuth();
$authUserId = $authUser['id'] ?? $authUser['user_id'] ?? null;
$db       = getDB();

if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    $stmt = $db->prepare(
        'SELECT id, name, email, phone, address, role FROM users WHERE id = ?'
    );
    $stmt->execute([$authUserId]);
    $user = $stmt->fetch();
    if (!$user) jsonError('User not found', 404);
    jsonResponse($user);
}

if ($_SERVER['REQUEST_METHOD'] === 'PATCH') {
    $body    = getBody();
    $name    = trim($body['name']    ?? '');
    $phone   = trim($body['phone']   ?? '');
    $address = trim($body['address'] ?? '');

    if (!$name) jsonError('Name is required');

    $db->prepare(
        'UPDATE users SET name = ?, phone = ?, address = ?, updated_at = NOW() WHERE id = ?'
    )->execute([$name, $phone ?: null, $address ?: null, $authUserId]);

    $stmt = $db->prepare(
        'SELECT id, name, email, phone, address, role FROM users WHERE id = ?'
    );
    $stmt->execute([$authUserId]);
    jsonResponse($stmt->fetch());
}

jsonError('Method not allowed', 405);
