<?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');

try {
    // Get parameters
    $area = isset($_GET['area']) ? mysqli_real_escape_string($con, $_GET['area']) : '';
    $limit = isset($_GET['limit']) ? (int)$_GET['limit'] : 100;
    
    if (empty($area)) {
        echo json_encode([
            'success' => false,
            'message' => 'Area parameter is required'
        ]);
        exit();
    }
    
    // Build query to get customers from specific area
    $query = "
        SELECT 
            c.ID,
            c.CustomerName,
            c.Mobile,
            c.AlternativePhone,
            c.Area,
            c.CustomerType,
            c.Address,
            c.GmapLocation,
            c.CreatedDate,
            COALESCE(
                (SELECT SUM(CASE WHEN TransactionType = 'Debit' THEN Amount ELSE -Amount END) 
                 FROM tblcustomerpayments cp 
                 WHERE cp.CustomerID = c.ID AND cp.Status = 'Completed' AND cp.IsActive = 1), 0
            ) as Outstanding
        FROM tblcustomers c
        WHERE c.IsActive = 1 
        AND c.Area = '$area'
        ORDER BY c.CustomerName ASC
        LIMIT $limit
    ";
    
    $result = mysqli_query($con, $query);
    
    if (!$result) {
        throw new Exception('Database query failed: ' . mysqli_error($con));
    }
    
    $customers = [];
    while ($row = mysqli_fetch_assoc($result)) {
        $customers[] = [
            'ID' => (int)$row['ID'],
            'CustomerName' => $row['CustomerName'],
            'Mobile' => $row['Mobile'],
            'AlternativePhone' => $row['AlternativePhone'],
            'Area' => $row['Area'],
            'CustomerType' => $row['CustomerType'],
            'Address' => $row['Address'],
            'GmapLocation' => $row['GmapLocation'],
            'Outstanding' => (float)$row['Outstanding'],
            'CreatedDate' => $row['CreatedDate']
        ];
    }
    
    // Get total count for the area
    $countQuery = "SELECT COUNT(*) as total FROM tblcustomers WHERE IsActive = 1 AND Area = '$area'";
    $countResult = mysqli_query($con, $countQuery);
    $totalCount = mysqli_fetch_assoc($countResult)['total'];
    
    echo json_encode([
        'success' => true,
        'data' => $customers,
        'area' => $area,
        'count' => count($customers),
        'total' => (int)$totalCount
    ]);
    
} catch (Exception $e) {
    error_log('Get customers by area error: ' . $e->getMessage());
    echo json_encode([
        'success' => false,
        'message' => 'Error: ' . $e->getMessage()
    ]);
}
?>