<?php
header("Content-Type: application/json");
error_reporting(E_ALL);
ini_set('display_errors', 1);

require_once 'auth_guard.php';
require_once '../config/database.php';
$db = getDB();

// Aggregates distinct profile variables directly from historical transaction records 
$query = "SELECT 
            full_name, 
            phone, 
            address, 
            COUNT(id) as order_frequency, 
            SUM(total) as individual_spend 
          FROM orders 
          GROUP BY phone 
          ORDER BY order_frequency DESC";

$result = $db->query($query);
$customers = [];

if ($result) {
    while ($row = $result->fetch_assoc()) {
        $customers[] = [
            "name" => $row['full_name'],
            "phone" => $row['phone'],
            "address" => $row['address'],
            "total_orders" => intval($row['order_frequency']),
            "total_spent" => floatval($row['individual_spend'])
        ];
    }
}

echo json_encode([
    "success" => true,
    "customers" => $customers
]);