<?php
session_start();
include '../layouts/dbconn.php';

// Set timezone to East Africa Time
date_default_timezone_set('Africa/Nairobi');

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

// Set headers for JSON response
header('Content-Type: application/json');

try {
    $customer_id = isset($_GET['id']) ? intval($_GET['id']) : 0;
    
    if (!$customer_id) {
        throw new Exception('Customer ID is required');
    }
    
    // Verify customer exists
    $checkSql = "SELECT customer_id FROM customers WHERE customer_id = ?";
    $stmt = $conn->prepare($checkSql);
    $stmt->bind_param("i", $customer_id);
    $stmt->execute();
    
    if ($stmt->get_result()->num_rows === 0) {
        throw new Exception('Customer not found');
    }
    
    // Get updated customer shipment statistics
    $sql_stats = "SELECT 
                    COUNT(*) as total_shipments,
                    COUNT(CASE WHEN status = 'DELIVERED' THEN 1 END) as delivered_shipments,
                    COUNT(CASE WHEN status IN ('BOOKED', 'COLLECTED', 'IN_TRANSIT', 'OUT_FOR_DELIVERY') THEN 1 END) as active_shipments,
                    COALESCE(SUM(total_charges), 0) as total_revenue,
                    COALESCE(SUM(CASE WHEN payment_status = 'PAID' THEN total_charges ELSE 0 END), 0) as paid_revenue,
                    COALESCE(SUM(CASE WHEN payment_status != 'PAID' THEN total_charges ELSE 0 END), 0) as outstanding_revenue,
                    COUNT(CASE WHEN DATE(booking_date) >= DATE_SUB(CURDATE(), INTERVAL 30 DAY) THEN 1 END) as recent_shipments
                  FROM shipments 
                  WHERE sender_customer_id = ?";
    
    $stmt = $conn->prepare($sql_stats);
    $stmt->bind_param("i", $customer_id);
    $stmt->execute();
    $stats = $stmt->get_result()->fetch_assoc();
    
    // Format the statistics for display
    $response = [
        'success' => true,
        'data' => [
            'total_shipments' => number_format($stats['total_shipments']),
            'delivered_shipments' => number_format($stats['delivered_shipments']),
            'active_shipments' => number_format($stats['active_shipments']),
            'total_revenue' => 'KES ' . number_format($stats['total_revenue']),
            'outstanding_revenue' => 'KES ' . number_format($stats['outstanding_revenue']),
            'recent_shipments' => number_format($stats['recent_shipments'])
        ],
        'raw_data' => $stats,
        'updated_at' => date('Y-m-d H:i:s')
    ];
    
    echo json_encode($response);
    
} catch (Exception $e) {
    // Log error for debugging
    error_log("Customer Stats Error: " . $e->getMessage());
    
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}

$conn->close();
?>