<?php
session_start();
include_once('../includes/config.php');

// Check if user is logged in
if (!isset($_SESSION['uid'])) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit();
}

// Set content type to JSON
header('Content-Type: application/json');

// Check if customer ID is provided
if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
    echo json_encode(['success' => false, 'message' => 'Invalid customer ID']);
    exit();
}

$customerId = (int)$_GET['id'];

// Fetch customer data with creator and updater information
$query = "SELECT c.*, u.FullName as CreatedByName, u2.FullName as UpdatedByName 
          FROM tblcustomers c 
          LEFT JOIN tblusers u ON c.CreatedBy = u.ID 
          LEFT JOIN tblusers u2 ON c.UpdatedBy = u2.ID 
          WHERE c.ID = $customerId AND c.IsActive = 1";

$result = mysqli_query($con, $query);

if (!$result) {
    echo json_encode(['success' => false, 'message' => 'Database error: ' . mysqli_error($con)]);
    exit();
}

if (mysqli_num_rows($result) == 0) {
    echo json_encode(['success' => false, 'message' => 'Customer not found']);
    exit();
}

$customer = mysqli_fetch_assoc($result);

// Return customer data
echo json_encode([
    'success' => true, 
    'customer' => $customer
]);
?>
