<?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'])) {
    header('Location: login.php');
    exit();
}

$user_id = $_SESSION['user_id'];
$customer_id = isset($_GET['id']) ? intval($_GET['id']) : 0;

if (!$customer_id) {
    $_SESSION['error_message'] = 'Invalid customer ID';
    header('Location: customers.php');
    exit();
}

// Fetch user details and role
$sql_user_details = "SELECT u.*, ur.role_name 
                     FROM users u 
                     INNER JOIN user_roles ur ON u.role_id = ur.role_id 
                     WHERE u.user_id = ?";
$stmt_user = $conn->prepare($sql_user_details);
$stmt_user->bind_param("i", $user_id);
$stmt_user->execute();
$user_details = $stmt_user->get_result()->fetch_assoc();

if ($user_details) {
    $username = $user_details['username'];
    $role_name = $user_details['role_name'];
    $full_name = $user_details['full_name'];
}

// Fetch customer details with creator information
$sql_customer = "SELECT c.*, 
                        creator.full_name as created_by_name,
                        updater.full_name as updated_by_name
                 FROM customers c
                 LEFT JOIN users creator ON c.created_by = creator.user_id
                 LEFT JOIN users updater ON c.created_by = updater.user_id
                 WHERE c.customer_id = ?";

$stmt_customer = $conn->prepare($sql_customer);
$stmt_customer->bind_param("i", $customer_id);
$stmt_customer->execute();
$customer = $stmt_customer->get_result()->fetch_assoc();

if (!$customer) {
    $_SESSION['error_message'] = 'Customer not found';
    header('Location: customers.php');
    exit();
}

// Get customer shipment statistics
$sql_shipment_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,
                        MIN(booking_date) as first_shipment_date,
                        MAX(booking_date) as last_shipment_date
                       FROM shipments 
                       WHERE sender_customer_id = ?";

$stmt_stats = $conn->prepare($sql_shipment_stats);
$stmt_stats->bind_param("i", $customer_id);
$stmt_stats->execute();
$shipment_stats = $stmt_stats->get_result()->fetch_assoc();

// Get recent shipments
$sql_recent_shipments = "SELECT s.*,
                                st.service_name,
                                ol.location_name as origin_location,
                                dl.location_name as destination_location
                         FROM shipments s
                         LEFT JOIN service_types st ON s.service_id = st.service_id
                         LEFT JOIN locations ol ON s.origin_location_id = ol.location_id
                         LEFT JOIN locations dl ON s.destination_location_id = dl.location_id
                         WHERE s.sender_customer_id = ?
                         ORDER BY s.created_at DESC
                         LIMIT 10";

$stmt_recent = $conn->prepare($sql_recent_shipments);
$stmt_recent->bind_param("i", $customer_id);
$stmt_recent->execute();
$recent_shipments = $stmt_recent->get_result();

// Get monthly shipment trends for chart (last 12 months)
$sql_monthly_trends = "SELECT 
                        DATE_FORMAT(booking_date, '%Y-%m') as month,
                        COUNT(*) as shipment_count,
                        SUM(total_charges) as monthly_revenue
                       FROM shipments 
                       WHERE sender_customer_id = ? 
                       AND booking_date >= DATE_SUB(CURDATE(), INTERVAL 12 MONTH)
                       GROUP BY DATE_FORMAT(booking_date, '%Y-%m')
                       ORDER BY month ASC";

$stmt_trends = $conn->prepare($sql_monthly_trends);
$stmt_trends->bind_param("i", $customer_id);
$stmt_trends->execute();
$monthly_trends = $stmt_trends->get_result();

$trend_data = [];
while ($trend = $monthly_trends->fetch_assoc()) {
    $trend_data[] = $trend;
}

// Get service type distribution
$sql_service_distribution = "SELECT 
                                st.service_name,
                                COUNT(s.shipment_id) as count,
                                SUM(s.total_charges) as revenue
                             FROM shipments s
                             INNER JOIN service_types st ON s.service_id = st.service_id
                             WHERE s.sender_customer_id = ?
                             GROUP BY st.service_id, st.service_name
                             ORDER BY count DESC";

$stmt_services = $conn->prepare($sql_service_distribution);
$stmt_services->bind_param("i", $customer_id);
$stmt_services->execute();
$service_distribution = $stmt_services->get_result();

$service_data = [];
while ($service = $service_distribution->fetch_assoc()) {
    $service_data[] = $service;
}

// Get recent activity logs
$sql_activity = "SELECT al.*, u.full_name as user_name
                 FROM activity_log al
                 LEFT JOIN users u ON al.user_id = u.user_id
                 WHERE al.module = 'customers' AND al.record_id = ?
                 ORDER BY al.logged_at DESC
                 LIMIT 10";

$stmt_activity = $conn->prepare($sql_activity);
$stmt_activity->bind_param("s", $customer_id);
$stmt_activity->execute();
$activity_logs = $stmt_activity->get_result();

$conn->close();
?>

<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Customer Details - ' . ($customer['customer_type'] == 'CORPORATE' ? $customer['company_name'] : $customer['first_name'] . ' ' . $customer['last_name']))); ?>
    
    <!-- Chart.js -->
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    
    <!-- SweetAlert2 -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@11.7.32/dist/sweetalert2.min.css">
    
    <!-- DataTables CSS -->
    <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.13.6/css/dataTables.bootstrap5.min.css">
    
    <?php include 'layouts/head-css.php'; ?>
    
    <style>
        /* Professional Customer Profile Theme */
        .page-content {
            padding: 1.5rem;
            background: #f8fafc;
        }
        
        .customer-header {
            background: linear-gradient(135deg, #1e40af 0%, #3b82f6 100%);
            color: white;
            border-radius: 12px;
            padding: 2rem;
            margin-bottom: 2rem;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
        }
        
        .customer-avatar {
            width: 80px;
            height: 80px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: 700;
            font-size: 1.5rem;
            color: white;
            background: rgba(255, 255, 255, 0.2);
            backdrop-filter: blur(10px);
            margin-right: 1.5rem;
        }
        
        .customer-info h2 {
            font-size: 1.75rem;
            font-weight: 700;
            margin-bottom: 0.5rem;
        }
        
        .customer-meta {
            display: flex;
            gap: 2rem;
            margin-top: 1rem;
            flex-wrap: wrap;
        }
        
        .meta-item {
            display: flex;
            align-items: center;
            gap: 0.5rem;
            font-size: 0.9rem;
            opacity: 0.9;
        }
        
        .info-card {
            background: white;
            border-radius: 12px;
            padding: 1.5rem;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
            border: 1px solid #e2e8f0;
            margin-bottom: 1.5rem;
            transition: all 0.2s ease;
        }
        
        .info-card:hover {
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
            transform: translateY(-2px);
        }
        
        .card-header {
            border-bottom: 1px solid #e2e8f0;
            padding-bottom: 1rem;
            margin-bottom: 1rem;
            display: flex;
            justify-content: between;
            align-items: center;
        }
        
        .card-title {
            font-size: 1.125rem;
            font-weight: 600;
            color: #1e293b;
            margin: 0;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }
        
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 1rem;
            margin-bottom: 2rem;
        }
        
        .stat-card {
            background: white;
            border-radius: 12px;
            padding: 1.5rem;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
            border: 1px solid #e2e8f0;
            text-align: center;
            transition: all 0.2s ease;
        }
        
        .stat-card:hover {
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
            transform: translateY(-2px);
        }
        
        .stat-value {
            font-size: 1.75rem;
            font-weight: 700;
            margin-bottom: 0.5rem;
        }
        
        .stat-label {
            font-size: 0.875rem;
            color: #64748b;
            text-transform: uppercase;
            letter-spacing: 0.05em;
            font-weight: 500;
        }
        
        .stat-change {
            font-size: 0.75rem;
            margin-top: 0.25rem;
        }
        
        .stat-change.positive { color: #059669; }
        .stat-change.negative { color: #dc2626; }
        .stat-change.neutral { color: #64748b; }
        
        /* Status badges */
        .status-badge {
            padding: 0.25rem 0.75rem;
            border-radius: 9999px;
            font-size: 0.75rem;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.05em;
        }
        
        .status-active {
            background: #dcfce7;
            color: #166534;
        }
        
        .status-inactive {
            background: #fef3c7;
            color: #92400e;
        }
        
        .status-suspended {
            background: #fee2e2;
            color: #991b1b;
        }
        
        .customer-type-badge {
            padding: 0.375rem 0.75rem;
            border-radius: 0.5rem;
            font-size: 0.875rem;
            font-weight: 600;
        }
        
        .type-corporate {
            background: #eff6ff;
            color: #1e40af;
        }
        
        .type-individual {
            background: #f0fdf4;
            color: #059669;
        }
        
        /* Action buttons */
        .action-buttons {
            display: flex;
            gap: 0.75rem;
            flex-wrap: wrap;
        }
        
        .btn {
            padding: 0.5rem 1rem;
            border-radius: 8px;
            border: none;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.2s ease;
            display: inline-flex;
            align-items: center;
            gap: 0.5rem;
            text-decoration: none;
            font-size: 0.875rem;
        }
        
        .btn-primary {
            background: #1e40af;
            color: white;
        }
        
        .btn-primary:hover {
            background: #1d4ed8;
            transform: translateY(-1px);
        }
        
        .btn-success {
            background: #059669;
            color: white;
        }
        
        .btn-warning {
            background: #d97706;
            color: white;
        }
        
        .btn-danger {
            background: #dc2626;
            color: white;
        }
        
        .btn-outline-primary {
            background: transparent;
            color: #1e40af;
            border: 1px solid #1e40af;
        }
        
        .btn-outline-primary:hover {
            background: #1e40af;
            color: white;
        }
        
        /* Table styles */
        .table {
            font-size: 0.875rem;
        }
        
        .table thead th {
            background: #f8fafc;
            border-bottom: 2px solid #e5e7eb;
            font-weight: 600;
            color: #374151;
            padding: 0.75rem;
        }
        
        .table tbody td {
            padding: 0.75rem;
            vertical-align: middle;
            border-bottom: 1px solid #f1f5f9;
        }
        
        .table tbody tr:hover {
            background: #f8fafc;
        }
        
        /* Charts */
        .chart-container {
            position: relative;
            height: 300px;
            margin: 1rem 0;
        }
        
        /* Info details */
        .info-details {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 1rem;
        }
        
        .detail-group {
            background: #f8fafc;
            border-radius: 8px;
            padding: 1rem;
        }
        
        .detail-label {
            font-size: 0.75rem;
            color: #64748b;
            text-transform: uppercase;
            letter-spacing: 0.05em;
            font-weight: 500;
            margin-bottom: 0.25rem;
        }
        
        .detail-value {
            font-size: 0.875rem;
            font-weight: 500;
            color: #1e293b;
        }
        
        .detail-value.empty {
            color: #94a3b8;
            font-style: italic;
        }
        
        /* Activity timeline */
        .activity-timeline {
            position: relative;
            padding-left: 2rem;
        }
        
        .activity-timeline::before {
            content: '';
            position: absolute;
            left: 0.75rem;
            top: 0;
            bottom: 0;
            width: 2px;
            background: #e2e8f0;
        }
        
        .activity-item {
            position: relative;
            margin-bottom: 1rem;
            padding-left: 1rem;
        }
        
        .activity-item::before {
            content: '';
            position: absolute;
            left: -0.375rem;
            top: 0.5rem;
            width: 0.75rem;
            height: 0.75rem;
            background: #3b82f6;
            border-radius: 50%;
            border: 2px solid white;
            box-shadow: 0 0 0 2px #e2e8f0;
        }
        
        .activity-content {
            background: white;
            border-radius: 8px;
            padding: 1rem;
            border: 1px solid #e2e8f0;
        }
        
        .activity-meta {
            font-size: 0.75rem;
            color: #64748b;
            margin-top: 0.5rem;
        }
        
        /* Responsive design */
        @media (max-width: 768px) {
            .page-content {
                padding: 1rem;
            }
            
            .customer-header {
                padding: 1.5rem;
            }
            
            .customer-header .d-flex {
                flex-direction: column;
                text-align: center;
            }
            
            .customer-avatar {
                margin: 0 auto 1rem;
            }
            
            .customer-meta {
                justify-content: center;
            }
            
            .action-buttons {
                justify-content: center;
            }
            
            .stats-grid {
                grid-template-columns: 1fr;
            }
        }
        
        /* Print styles */
        @media print {
            .action-buttons,
            .no-print {
                display: none !important;
            }
        }
    </style>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    
                    <!-- Page Title -->
                    <div class="row">
                        <div class="col-12">
                            <div class="page-title-box d-sm-flex align-items-center justify-content-between">
                                <h4 class="mb-sm-0 font-size-18">Customer Profile</h4>
                                <div class="page-title-right">
                                    <ol class="breadcrumb m-0">
                                        <li class="breadcrumb-item"><a href="index.php">Dashboard</a></li>
                                        <li class="breadcrumb-item"><a href="customers.php">Customers</a></li>
                                        <li class="breadcrumb-item active">Customer Details</li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Customer Header -->
                    <div class="customer-header">
                        <div class="d-flex align-items-center">
                            <div class="customer-avatar">
                                <?php 
                                if ($customer['customer_type'] == 'CORPORATE') {
                                    echo strtoupper(substr($customer['company_name'] ?? 'CO', 0, 2));
                                } else {
                                    echo strtoupper(substr($customer['first_name'] ?? 'C', 0, 1) . substr($customer['last_name'] ?? 'U', 0, 1));
                                }
                                ?>
                            </div>
                            <div class="customer-info flex-grow-1">
                                <h2>
                                    <?php 
                                    echo $customer['customer_type'] == 'CORPORATE' 
                                        ? ($customer['company_name'] ?? 'N/A')
                                        : ($customer['first_name'] . ' ' . $customer['last_name']);
                                    ?>
                                </h2>
                                <div class="customer-meta">
                                    <div class="meta-item">
                                        <i class="bx bx-id-card"></i>
                                        <span><?php echo $customer['customer_code']; ?></span>
                                    </div>
                                    <div class="meta-item">
                                        <i class="bx <?php echo $customer['customer_type'] == 'CORPORATE' ? 'bx-buildings' : 'bx-user'; ?>"></i>
                                        <span class="customer-type-badge <?php echo $customer['customer_type'] == 'CORPORATE' ? 'type-corporate' : 'type-individual'; ?>">
                                            <?php echo ucfirst(strtolower($customer['customer_type'])); ?>
                                        </span>
                                    </div>
                                    <div class="meta-item">
                                        <i class="bx bx-check-shield"></i>
                                        <span class="status-badge status-<?php echo strtolower($customer['status']); ?>">
                                            <?php echo ucfirst(strtolower($customer['status'])); ?>
                                        </span>
                                    </div>
                                    <div class="meta-item">
                                        <i class="bx bx-calendar"></i>
                                        <span>Member since <?php echo date('M Y', strtotime($customer['created_at'])); ?></span>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="action-buttons mt-3 no-print">
                            <a href="create_shipment.php?customer_id=<?php echo $customer_id; ?>" class="btn btn-success">
                                <i class="bx bx-package"></i> New Shipment
                            </a>
                            <a href="edit_customer.php?id=<?php echo $customer_id; ?>" class="btn btn-warning">
                                <i class="bx bx-edit"></i> Edit Customer
                            </a>
                            <button type="button" class="btn btn-primary" onclick="generateReport()">
                                <i class="bx bx-file-pdf"></i> Generate Report
                            </button>
                            <button type="button" class="btn btn-outline-primary" onclick="window.print()">
                                <i class="bx bx-printer"></i> Print Profile
                            </button>
                            <a href="customers.php" class="btn btn-outline-primary">
                                <i class="bx bx-arrow-back"></i> Back to List
                            </a>
                        </div>
                    </div>
                    
                    <!-- Statistics Cards -->
                    <div class="stats-grid">
                        <div class="stat-card">
                            <div class="stat-value text-primary"><?php echo number_format($shipment_stats['total_shipments']); ?></div>
                            <div class="stat-label">Total Shipments</div>
                            <div class="stat-change neutral">All time</div>
                        </div>
                        
                        <div class="stat-card">
                            <div class="stat-value text-success"><?php echo number_format($shipment_stats['delivered_shipments']); ?></div>
                            <div class="stat-label">Delivered</div>
                            <div class="stat-change positive">
                                <?php 
                                $delivery_rate = $shipment_stats['total_shipments'] > 0 
                                    ? round(($shipment_stats['delivered_shipments'] / $shipment_stats['total_shipments']) * 100, 1) 
                                    : 0;
                                echo $delivery_rate . '% success rate';
                                ?>
                            </div>
                        </div>
                        
                        <div class="stat-card">
                            <div class="stat-value text-warning"><?php echo number_format($shipment_stats['active_shipments']); ?></div>
                            <div class="stat-label">Active Shipments</div>
                            <div class="stat-change <?php echo $shipment_stats['active_shipments'] > 0 ? 'positive' : 'neutral'; ?>">
                                Currently in transit
                            </div>
                        </div>
                        
                        <div class="stat-card">
                            <div class="stat-value text-info">KES <?php echo number_format($shipment_stats['total_revenue']); ?></div>
                            <div class="stat-label">Total Revenue</div>
                            <div class="stat-change <?php echo $shipment_stats['paid_revenue'] >= $shipment_stats['outstanding_revenue'] ? 'positive' : 'negative'; ?>">
                                KES <?php echo number_format($shipment_stats['paid_revenue']); ?> paid
                            </div>
                        </div>
                        
                        <div class="stat-card">
                            <div class="stat-value text-danger">KES <?php echo number_format($shipment_stats['outstanding_revenue']); ?></div>
                            <div class="stat-label">Outstanding</div>
                            <div class="stat-change <?php echo $shipment_stats['outstanding_revenue'] > 0 ? 'negative' : 'positive'; ?>">
                                <?php 
                                $outstanding_percent = $shipment_stats['total_revenue'] > 0 
                                    ? round(($shipment_stats['outstanding_revenue'] / $shipment_stats['total_revenue']) * 100, 1) 
                                    : 0;
                                echo $outstanding_percent . '% unpaid';
                                ?>
                            </div>
                        </div>
                        
                        <div class="stat-card">
                            <div class="stat-value text-secondary"><?php echo number_format($shipment_stats['recent_shipments']); ?></div>
                            <div class="stat-label">Recent Activity</div>
                            <div class="stat-change neutral">Last 30 days</div>
                        </div>
                    </div>
                    
                    <!-- Main Content Grid -->
                    <div class="row">
                        <div class="col-xl-8">
                            <!-- Shipment Trends Chart -->
                            <div class="info-card">
                                <div class="card-header">
                                    <h3 class="card-title">
                                        <i class="bx bx-trending-up"></i>
                                        Shipment Trends (Last 12 Months)
                                    </h3>
                                </div>
                                <div class="chart-container">
                                    <canvas id="trendsChart"></canvas>
                                </div>
                            </div>
                            
                            <!-- Recent Shipments -->
                            <div class="info-card">
                                <div class="card-header">
                                    <h3 class="card-title">
                                        <i class="bx bx-package"></i>
                                        Recent Shipments
                                    </h3>
                                    <a href="shipments.php?customer_id=<?php echo $customer_id; ?>" class="btn btn-outline-primary btn-sm">
                                        View All
                                    </a>
                                </div>
                                <div class="table-responsive">
                                    <table class="table table-hover">
                                        <thead>
                                            <tr>
                                                <th>Tracking #</th>
                                                <th>Route</th>
                                                <th>Service</th>
                                                <th>Status</th>
                                                <th>Amount</th>
                                                <th>Date</th>
                                                <th>Actions</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php while($shipment = $recent_shipments->fetch_assoc()): ?>
                                            <tr>
                                                <td>
                                                    <a href="view_shipment.php?tracking=<?php echo $shipment['tracking_number']; ?>" class="fw-bold text-primary">
                                                        <?php echo $shipment['tracking_number']; ?>
                                                    </a>
                                                </td>
                                                <td>
                                                    <div>
                                                        <div class="fw-medium"><?php echo $shipment['origin_location']; ?></div>
                                                        <small class="text-muted">to <?php echo $shipment['destination_location']; ?></small>
                                                    </div>
                                                </td>
                                                <td><?php echo $shipment['service_name']; ?></td>
                                                <td>
                                                    <span class="status-badge status-<?php echo strtolower(str_replace('_', '-', $shipment['status'])); ?>">
                                                        <?php echo ucfirst(strtolower(str_replace('_', ' ', $shipment['status']))); ?>
                                                    </span>
                                                </td>
                                                <td class="fw-bold">KES <?php echo number_format($shipment['total_charges']); ?></td>
                                                <td><?php echo date('M j, Y', strtotime($shipment['booking_date'])); ?></td>
                                                <td>
                                                    <a href="view_shipment.php?tracking=<?php echo $shipment['tracking_number']; ?>" class="btn btn-sm btn-outline-primary" title="View Shipment">
                                                        <i class="bx bx-show"></i>
                                                    </a>
                                                </td>
                                            </tr>
                                            <?php endwhile; ?>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                        
                        <div class="col-xl-4">
                            <!-- Customer Information -->
                            <div class="info-card">
                                <div class="card-header">
                                    <h3 class="card-title">
                                        <i class="bx bx-info-circle"></i>
                                        Contact Information
                                    </h3>
                                </div>
                                <div class="info-details">
                                    <div class="detail-group">
                                        <div class="detail-label">Phone Number</div>
                                        <div class="detail-value">
                                            <a href="mailto:<?php echo $customer['email']; ?>" class="text-primary">
                                                <i class="bx bx-envelope"></i> <?php echo $customer['email']; ?>
                                            </a>
                                        </div>
                                    </div>
                                </div>
                                
                                <div class="info-details mt-3">
                                    <div class="detail-group">
                                        <div class="detail-label">Address</div>
                                        <div class="detail-value">
                                            <div><?php echo $customer['address_line1']; ?></div>
                                            <?php if($customer['address_line2']): ?>
                                            <div><?php echo $customer['address_line2']; ?></div>
                                            <?php endif; ?>
                                            <div><?php echo $customer['city'] . ', ' . $customer['state']; ?></div>
                                            <div><?php echo $customer['country'] . ' ' . $customer['postal_code']; ?></div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Credit Information -->
                            <?php if($customer['is_credit_customer']): ?>
                            <div class="info-card">
                                <div class="card-header">
                                    <h3 class="card-title">
                                        <i class="bx bx-credit-card"></i>
                                        Credit Information
                                    </h3>
                                </div>
                                <div class="info-details">
                                    <div class="detail-group">
                                        <div class="detail-label">Credit Limit</div>
                                        <div class="detail-value text-success fw-bold">
                                            KES <?php echo number_format($customer['credit_limit']); ?>
                                        </div>
                                    </div>
                                    
                                    <div class="detail-group">
                                        <div class="detail-label">Payment Terms</div>
                                        <div class="detail-value">
                                            <?php echo $customer['payment_terms']; ?> days
                                        </div>
                                    </div>
                                    
                                    <div class="detail-group">
                                        <div class="detail-label">Outstanding Amount</div>
                                        <div class="detail-value <?php echo $shipment_stats['outstanding_revenue'] > 0 ? 'text-danger' : 'text-success'; ?> fw-bold">
                                            KES <?php echo number_format($shipment_stats['outstanding_revenue']); ?>
                                        </div>
                                    </div>
                                    
                                    <div class="detail-group">
                                        <div class="detail-label">Available Credit</div>
                                        <div class="detail-value fw-bold">
                                            KES <?php echo number_format($customer['credit_limit'] - $shipment_stats['outstanding_revenue']); ?>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <?php endif; ?>
                            
                            <!-- Service Distribution -->
                            <div class="info-card">
                                <div class="card-header">
                                    <h3 class="card-title">
                                        <i class="bx bx-pie-chart-alt-2"></i>
                                        Service Distribution
                                    </h3>
                                </div>
                                <div class="chart-container">
                                    <canvas id="serviceChart"></canvas>
                                </div>
                            </div>
                            
                            <!-- Customer Details -->
                            <div class="info-card">
                                <div class="card-header">
                                    <h3 class="card-title">
                                        <i class="bx bx-detail"></i>
                                        Additional Details
                                    </h3>
                                </div>
                                <div class="info-details">
                                    <?php if($customer['tax_id']): ?>
                                    <div class="detail-group">
                                        <div class="detail-label">Tax ID</div>
                                        <div class="detail-value"><?php echo $customer['tax_id']; ?></div>
                                    </div>
                                    <?php endif; ?>
                                    
                                    <div class="detail-group">
                                        <div class="detail-label">Customer Since</div>
                                        <div class="detail-value">
                                            <?php echo date('F j, Y', strtotime($customer['created_at'])); ?>
                                        </div>
                                    </div>
                                    
                                    <div class="detail-group">
                                        <div class="detail-label">Created By</div>
                                        <div class="detail-value">
                                            <?php echo $customer['created_by_name'] ?? 'System'; ?>
                                        </div>
                                    </div>
                                    
                                    <div class="detail-group">
                                        <div class="detail-label">Last Updated</div>
                                        <div class="detail-value">
                                            <?php echo date('F j, Y g:i A', strtotime($customer['updated_at'])); ?>
                                        </div>
                                    </div>
                                    
                                    <?php if($shipment_stats['first_shipment_date']): ?>
                                    <div class="detail-group">
                                        <div class="detail-label">First Shipment</div>
                                        <div class="detail-value">
                                            <?php echo date('F j, Y', strtotime($shipment_stats['first_shipment_date'])); ?>
                                        </div>
                                    </div>
                                    
                                    <div class="detail-group">
                                        <div class="detail-label">Last Shipment</div>
                                        <div class="detail-value">
                                            <?php echo date('F j, Y', strtotime($shipment_stats['last_shipment_date'])); ?>
                                        </div>
                                    </div>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Activity Timeline -->
                    <div class="row">
                        <div class="col-12">
                            <div class="info-card">
                                <div class="card-header">
                                    <h3 class="card-title">
                                        <i class="bx bx-history"></i>
                                        Recent Activity
                                    </h3>
                                </div>
                                <div class="activity-timeline">
                                    <?php while($activity = $activity_logs->fetch_assoc()): ?>
                                    <div class="activity-item">
                                        <div class="activity-content">
                                            <div class="fw-medium">
                                                <?php 
                                                $actionText = ucfirst(strtolower($activity['action']));
                                                echo $actionText . ' customer record';
                                                ?>
                                            </div>
                                            <?php if($activity['old_values'] || $activity['new_values']): ?>
                                            <div class="activity-details mt-2">
                                                <?php
                                                if($activity['old_values']) {
                                                    $oldValues = json_decode($activity['old_values'], true);
                                                    if($oldValues) {
                                                        echo '<small class="text-muted">Previous: ' . implode(', ', array_map(function($k, $v) {
                                                            return "$k: $v";
                                                        }, array_keys($oldValues), $oldValues)) . '</small><br>';
                                                    }
                                                }
                                                if($activity['new_values']) {
                                                    $newValues = json_decode($activity['new_values'], true);
                                                    if($newValues) {
                                                        echo '<small class="text-success">Updated: ' . implode(', ', array_map(function($k, $v) {
                                                            return "$k: $v";
                                                        }, array_keys($newValues), $newValues)) . '</small>';
                                                    }
                                                }
                                                ?>
                                            </div>
                                            <?php endif; ?>
                                            <div class="activity-meta">
                                                <i class="bx bx-user"></i> <?php echo $activity['user_name'] ?? 'System'; ?>
                                                <i class="bx bx-time ms-3"></i> <?php echo date('M j, Y g:i A', strtotime($activity['logged_at'])); ?>
                                                <?php if($activity['ip_address']): ?>
                                                <i class="bx bx-globe ms-3"></i> <?php echo $activity['ip_address']; ?>
                                                <?php endif; ?>
                                            </div>
                                        </div>
                                    </div>
                                    <?php endwhile; ?>
                                    
                                    <?php if($activity_logs->num_rows === 0): ?>
                                    <div class="text-center text-muted py-4">
                                        <i class="bx bx-history" style="font-size: 3rem; opacity: 0.5;"></i>
                                        <p class="mt-2">No recent activity found</p>
                                    </div>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>
    
    <?php include 'layouts/vendor-scripts.php'; ?>
    
    <!-- jQuery -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    
    <!-- SweetAlert2 -->
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11.7.32/dist/sweetalert2.all.min.js"></script>
    
    <!-- DataTables JS -->
    <script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.6/js/dataTables.bootstrap5.min.js"></script>
    
    <script>
    $(document).ready(function() {
        // Initialize charts
        initializeTrendsChart();
        initializeServiceChart();
        
        // Show success message if redirected from customer list
        if (window.location.search.includes('from=list')) {
            Swal.fire({
                title: 'Customer Profile Loaded',
                text: 'Here you can view detailed customer information and shipment history.',
                icon: 'info',
                timer: 3000,
                timerProgressBar: true,
                showConfirmButton: false
            });
        }
    });
    
    function initializeTrendsChart() {
        const trendData = <?php echo json_encode($trend_data); ?>;
        
        const ctx = document.getElementById('trendsChart').getContext('2d');
        
        const labels = trendData.map(item => {
            const date = new Date(item.month + '-01');
            return date.toLocaleDateString('en-US', { month: 'short', year: 'numeric' });
        });
        
        const shipmentData = trendData.map(item => parseInt(item.shipment_count));
        const revenueData = trendData.map(item => parseFloat(item.monthly_revenue));
        
        new Chart(ctx, {
            type: 'line',
            data: {
                labels: labels,
                datasets: [{
                    label: 'Shipments',
                    data: shipmentData,
                    borderColor: '#3b82f6',
                    backgroundColor: 'rgba(59, 130, 246, 0.1)',
                    tension: 0.4,
                    yAxisID: 'y'
                }, {
                    label: 'Revenue (KES)',
                    data: revenueData,
                    borderColor: '#059669',
                    backgroundColor: 'rgba(5, 150, 105, 0.1)',
                    tension: 0.4,
                    yAxisID: 'y1'
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                interaction: {
                    mode: 'index',
                    intersect: false,
                },
                plugins: {
                    legend: {
                        position: 'top',
                    }
                },
                scales: {
                    x: {
                        display: true,
                        title: {
                            display: true,
                            text: 'Month'
                        }
                    },
                    y: {
                        type: 'linear',
                        display: true,
                        position: 'left',
                        title: {
                            display: true,
                            text: 'Shipments'
                        }
                    },
                    y1: {
                        type: 'linear',
                        display: true,
                        position: 'right',
                        title: {
                            display: true,
                            text: 'Revenue (KES)'
                        },
                        grid: {
                            drawOnChartArea: false,
                        },
                    }
                }
            }
        });
    }
    
    function initializeServiceChart() {
        const serviceData = <?php echo json_encode($service_data); ?>;
        
        if (serviceData.length === 0) {
            document.getElementById('serviceChart').closest('.chart-container').innerHTML = 
                '<div class="text-center text-muted py-4">' +
                '<i class="bx bx-pie-chart-alt-2" style="font-size: 3rem; opacity: 0.5;"></i>' +
                '<p class="mt-2">No service data available</p>' +
                '</div>';
            return;
        }
        
        const ctx = document.getElementById('serviceChart').getContext('2d');
        
        const labels = serviceData.map(item => item.service_name);
        const data = serviceData.map(item => parseInt(item.count));
        const colors = ['#3b82f6', '#059669', '#d97706', '#7c3aed', '#dc2626', '#0891b2'];
        
        new Chart(ctx, {
            type: 'doughnut',
            data: {
                labels: labels,
                datasets: [{
                    data: data,
                    backgroundColor: colors.slice(0, data.length),
                    borderWidth: 2,
                    borderColor: '#ffffff'
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        position: 'bottom',
                        labels: {
                            padding: 20,
                            usePointStyle: true
                        }
                    },
                    tooltip: {
                        callbacks: {
                            label: function(context) {
                                const service = serviceData[context.dataIndex];
                                return context.label + ': ' + context.parsed + ' shipments (KES ' + 
                                       parseFloat(service.revenue).toLocaleString() + ')';
                            }
                        }
                    }
                }
            }
        });
    }
    
    function generateReport() {
        Swal.fire({
            title: 'Generate Customer Report',
            text: 'Select the type of report you want to generate:',
            icon: 'question',
            showCancelButton: true,
            showDenyButton: true,
            confirmButtonText: '<i class="bx bx-file-pdf"></i> Detailed PDF',
            denyButtonText: '<i class="bx bx-table"></i> Summary Excel',
            cancelButtonText: 'Cancel',
            confirmButtonColor: '#dc2626',
            denyButtonColor: '#059669',
            cancelButtonColor: '#64748b'
        }).then((result) => {
            if (result.isConfirmed) {
                // Generate PDF report
                window.open('reports/customer_report.php?id=<?php echo $customer_id; ?>&format=pdf', '_blank');
                
                Swal.fire({
                    title: 'Generating PDF Report...',
                    text: 'Your detailed PDF report is being prepared.',
                    icon: 'info',
                    timer: 2000,
                    timerProgressBar: true,
                    showConfirmButton: false
                });
            } else if (result.isDenied) {
                // Generate Excel report
                window.open('reports/customer_report.php?id=<?php echo $customer_id; ?>&format=excel', '_blank');
                
                Swal.fire({
                    title: 'Generating Excel Report...',
                    text: 'Your Excel summary is being prepared.',
                    icon: 'info',
                    timer: 2000,
                    timerProgressBar: true,
                    showConfirmButton: false
                });
            }
        });
    }
    
    // Auto-refresh customer data every 2 minutes
    setInterval(function() {
        if (document.visibilityState === 'visible') {
            // Refresh statistics quietly
            fetch('ajax/customer_stats.php?id=<?php echo $customer_id; ?>')
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        // Update stat values
                        document.querySelectorAll('.stat-value').forEach((element, index) => {
                            if (data.stats && data.stats[index]) {
                                element.textContent = data.stats[index];
                            }
                        });
                    }
                })
                .catch(error => console.log('Auto-refresh failed:', error));
        }
    }, 120000); // 2 minutes
    
    // Keyboard shortcuts
    $(document).keydown(function(e) {
        // Ctrl/Cmd + N for new shipment
        if ((e.ctrlKey || e.metaKey) && e.key === 'n') {
            e.preventDefault();
            window.location.href = 'create_shipment.php?customer_id=<?php echo $customer_id; ?>';
        }
        
        // Ctrl/Cmd + E for edit customer
        if ((e.ctrlKey || e.metaKey) && e.key === 'e') {
            e.preventDefault();
            window.location.href = 'edit_customer.php?id=<?php echo $customer_id; ?>';
        }
        
        // Ctrl/Cmd + P for print
        if ((e.ctrlKey || e.metaKey) && e.key === 'p') {
            e.preventDefault();
            window.print();
        }
        
        // Ctrl/Cmd + B for back to list
        if ((e.ctrlKey || e.metaKey) && e.key === 'b') {
            e.preventDefault();
            window.location.href = 'customers.php';
        }
    });
    
    // Add keyboard shortcuts help
    function showKeyboardShortcuts() {
        Swal.fire({
            title: 'Keyboard Shortcuts',
            html: `
                <div class="text-start">
                    <p><kbd>Ctrl/Cmd + N</kbd> - New shipment for this customer</p>
                    <p><kbd>Ctrl/Cmd + E</kbd> - Edit customer details</p>
                    <p><kbd>Ctrl/Cmd + P</kbd> - Print customer profile</p>
                    <p><kbd>Ctrl/Cmd + B</kbd> - Back to customer list</p>
                </div>
            `,
            icon: 'info',
            confirmButtonColor: '#3b82f6'
        });
    }
    
    // Add help button to page
    $(document).ready(function() {
        $('.page-title-right').append(`
            <button type="button" class="btn btn-outline-secondary btn-sm ms-2" onclick="showKeyboardShortcuts()" title="Keyboard Shortcuts">
                <i class="bx bx-help-circle"></i>
            </button>
        `);
    });
    </script>
    
    <!-- App js -->
    <script src="assets/js/app.js"></script>
</body>
</html>