<?php
/**
 * Rig N Dig - Mobile API v1 / Profile
 */
header('Content-Type: application/json');
require_once '../../../config/config.php';
require_once '../../../includes/functions.php';
require_once '../api_helper.php';

$user = authenticateAPI();

if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    apiResponse(true, 'Profile loaded', $user);
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = sanitize($_POST['name'] ?? $user['contact_name']);
    $company = sanitize($_POST['company'] ?? $user['company_name']);
    $phone = sanitize($_POST['phone'] ?? $user['phone']);
    $email = trim($_POST['email'] ?? $user['email']);

    // Check if email already used by another user
    if ($email !== $user['email']) {
        $existing = Database::fetchOne("SELECT id FROM customers WHERE email = ? AND id != ?", [$email, $user['id']]);
        if ($existing) {
            apiResponse(false, 'Email already in use by another account');
        }
    }

    try {
        Database::execute(
            "UPDATE customers SET contact_name = ?, company_name = ?, phone = ?, email = ? WHERE id = ?",
            [$name, $company, $phone, $email, $user['id']]
        );
        
        $updatedUser = Database::fetchOne("SELECT id, company_name, contact_name, email, phone FROM customers WHERE id = ?", [$user['id']]);
        apiResponse(true, 'Profile updated successfully', $updatedUser);
    } catch (Exception $e) {
        apiResponse(false, 'Update failed: ' . $e->getMessage());
    }
}
