<?php 
include 'layouts/session.php';
include 'layouts/main.php';
include 'layouts/dbconn.php';

// Get customer ID from URL parameter
$customer_id = isset($_GET['id']) ? intval($_GET['id']) : 0;

if ($customer_id <= 0) {
    $_SESSION['error_message'] = "Invalid customer ID";
    header("Location: all_customers.php");
    exit();
}

// Fetch customer data
$query = "SELECT * FROM customers WHERE customer_id = ?";
$stmt = $conn->prepare($query);
$stmt->bind_param("i", $customer_id);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 0) {
    $_SESSION['error_message'] = "Customer not found";
    header("Location: all_customers.php");
    exit();
}

$customer = $result->fetch_assoc();

// Get status label and class
$statusLabel = ($customer['status'] == 1) ? 'Active' : 'Inactive';
$statusClass = ($customer['status'] == 1) ? 'badge bg-success' : 'badge bg-danger';

// Get shipment count for this customer
$shipmentQuery = "SELECT COUNT(*) as shipment_count FROM files WHERE customer = ?";
$shipmentStmt = $conn->prepare($shipmentQuery);
$shipmentStmt->bind_param("i", $customer_id);
$shipmentStmt->execute();
$shipmentResult = $shipmentStmt->get_result();
$shipmentData = $shipmentResult->fetch_assoc();
$shipmentCount = $shipmentData['shipment_count'] ?? 0;

// Get recent files/shipments for this customer
$recentShipmentsQuery = "SELECT file_number, created_date, destination, `local/transit` as type, close_file 
                         FROM files 
                         WHERE customer = ? 
                         ORDER BY created_date DESC 
                         LIMIT 5";
$recentStmt = $conn->prepare($recentShipmentsQuery);
$recentStmt->bind_param("i", $customer_id);
$recentStmt->execute();
$recentShipments = $recentStmt->get_result();

// Check for debt records
$debtQuery = "SELECT * FROM client_debts WHERE customer_id = ?";
$debtStmt = $conn->prepare($debtQuery);
$debtStmt->bind_param("i", $customer_id);
$debtStmt->execute();
$debtResult = $debtStmt->get_result();
$debtData = $debtResult->fetch_assoc();

// Format customer name correctly
$customerName = trim($customer['first_name'] . ' ' . $customer['last_name']);
if (empty($customerName)) {
    $customerName = "Customer #" . $customer_id;
}

// Set the default profile image
$profileInitial = strtoupper(substr($customerName, 0, 1));
?>

<!doctype html>
<html lang="en" data-layout="vertical" data-topbar="light" data-sidebar="dark" data-sidebar-size="lg" data-sidebar-image="none" data-preloader="disable">

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Customer Profile')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <style>
        .customer-avatar {
            width: 100px;
            height: 100px;
            background-color: #5156be;
            color: #fff;
            font-size: 48px;
            display: flex;
            align-items: center;
            justify-content: center;
            border-radius: 50%;
            margin-right: 20px;
        }
        
        .customer-header {
            display: flex;
            align-items: center;
            margin-bottom: 20px;
        }
        
        .custom-badge {
            font-size: 14px;
            padding: 8px 12px;
        }
        
        .mini-stat-card {
            transition: all 0.3s ease;
            border-radius: 10px;
            overflow: hidden;
            box-shadow: 0 2px 4px rgba(0,0,0,0.05);
        }
        
        .mini-stat-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
        }
        
        .bg-gradient-primary {
            background: linear-gradient(135deg, #5156be 0%, #7d80d3 100%);
        }
        
        .bg-gradient-success {
            background: linear-gradient(135deg, #0ab39c 0%, #2ed8b6 100%);
        }
        
        .bg-gradient-info {
            background: linear-gradient(135deg, #299cdb 0%, #57c9f2 100%);
        }
        
        .mini-stat-icon {
            font-size: 24px;
            width: 48px;
            height: 48px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            background-color: rgba(255, 255, 255, 0.2);
        }
        
        .activity-timeline .activity-item {
            position: relative;
            padding-left: 45px;
            margin-bottom: 20px;
        }
        
        .activity-timeline .activity-item:before {
            content: "";
            position: absolute;
            left: 20px;
            top: 0;
            bottom: -20px;
            width: 2px;
            background-color: #f0f0f0;
        }
        
        .activity-timeline .activity-item:last-child:before {
            display: none;
        }
        
        .activity-icon {
            position: absolute;
            left: 0;
            top: 0;
            width: 40px;
            height: 40px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 16px;
            z-index: 2;
        }
        
        .shipment-status {
            height: 10px;
            width: 10px;
            display: inline-block;
            border-radius: 50%;
            margin-right: 5px;
        }
        
        .file-card {
            border-left: 4px solid transparent;
            transition: all 0.3s ease;
        }
        
        .file-card:hover {
            transform: translateX(5px);
            border-left: 4px solid #5156be;
        }
        
        .file-card-transit {
            border-left-color: #299cdb;
        }
        
        .file-card-local {
            border-left-color: #0ab39c;
        }
        
        .file-card-closed {
            border-left-color: #f06548;
        }
        
        .file-icon {
            font-size: 24px;
            color: #5156be;
        }
        
        .customer-tag {
            display: inline-block;
            padding: 5px 10px;
            border-radius: 5px;
            margin-right: 5px;
            margin-bottom: 5px;
            background-color: #f0f2f7;
            font-size: 12px;
        }
    </style>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <?php includeFileWithVariables('layouts/page-title.php', array('pagetitle' => 'Customer Management', 'title' => 'Customer Profile')); ?>

                    <!-- Display success/error messages if they exist -->
                    <?php if(isset($_SESSION['success_message'])): ?>
                        <div class="alert alert-success alert-dismissible fade show" role="alert">
                            <?php echo $_SESSION['success_message']; unset($_SESSION['success_message']); ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                        </div>
                    <?php endif; ?>
                    
                    <?php if(isset($_SESSION['error_message'])): ?>
                        <div class="alert alert-danger alert-dismissible fade show" role="alert">
                            <?php echo $_SESSION['error_message']; unset($_SESSION['error_message']); ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                        </div>
                    <?php endif; ?>

                    <div class="row">
                        <div class="col-12">
                            <div class="card">
                                <div class="card-body">
                                    <div class="d-flex justify-content-between align-items-center mb-4">
                                        <div class="customer-header">
                                            <div class="customer-avatar">
                                                <?php echo $profileInitial; ?>
                                            </div>
                                            <div>
                                                <h3 class="fw-semibold mb-1"><?php echo htmlspecialchars($customerName); ?></h3>
                                                <p class="text-muted mb-2">
                                                    <i class="ri-map-pin-line me-1"></i> <?php echo htmlspecialchars($customer['city'] ? $customer['city'] . ', ' : ''); ?><?php echo htmlspecialchars($customer['country'] ?: 'No location specified'); ?>
                                                </p>
                                                <div>
                                                    <span class="badge <?php echo $statusClass; ?> custom-badge">
                                                        <i class="ri-checkbox-circle-line me-1"></i> <?php echo $statusLabel; ?> Customer
                                                    </span>
                                                    <?php if($customer['invoices_count'] > 0): ?>
                                                    <span class="badge bg-info custom-badge ms-2">
                                                        <i class="ri-file-list-3-line me-1"></i> <?php echo $customer['invoices_count']; ?> Invoices
                                                    </span>
                                                    <?php endif; ?>
                                                </div>
                                            </div>
                                        </div>
                                        <div>
                                            <div class="dropdown">
                                                <button class="btn btn-soft-primary btn-icon btn-sm" type="button" data-bs-toggle="dropdown" aria-expanded="false">
                                                    <i class="ri-more-2-fill"></i>
                                                </button>
                                                <ul class="dropdown-menu dropdown-menu-end">
                                                    <li>
                                                        <a class="dropdown-item" href="edit_customer.php?id=<?php echo $customer_id; ?>">
                                                            <i class="ri-pencil-fill align-bottom me-2 text-muted"></i> Edit Profile
                                                        </a>
                                                    </li>
                                                    <li>
                                                        <a class="dropdown-item" href="new_shipment.php?customer=<?php echo $customer_id; ?>">
                                                            <i class="ri-ship-line align-bottom me-2 text-muted"></i> Create Shipment
                                                        </a>
                                                    </li>
                                                    <li>
                                                        <a class="dropdown-item" href="generate_report.php?customer=<?php echo $customer_id; ?>">
                                                            <i class="ri-file-chart-line align-bottom me-2 text-muted"></i> Generate Report
                                                        </a>
                                                    </li>
                                                    <li><hr class="dropdown-divider"></li>
                                                    <?php if($customer['status'] == 1): ?>
                                                    <li>
                                                        <a class="dropdown-item text-danger" href="javascript:void(0);" onclick="deactivateCustomer()">
                                                            <i class="ri-close-circle-fill align-bottom me-2 text-danger"></i> Deactivate Customer
                                                        </a>
                                                    </li>
                                                    <?php else: ?>
                                                    <li>
                                                        <a class="dropdown-item text-success" href="javascript:void(0);" onclick="activateCustomer()">
                                                            <i class="ri-check-circle-fill align-bottom me-2 text-success"></i> Activate Customer
                                                        </a>
                                                    </li>
                                                    <?php endif; ?>
                                                </ul>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Stats Cards -->
                    <div class="row">
                        <div class="col-md-4">
                            <div class="card mini-stat-card bg-gradient-primary text-white">
                                <div class="card-body">
                                    <div class="d-flex align-items-center">
                                        <div class="flex-grow-1">
                                            <h6 class="text-white-50">Total Shipments</h6>
                                            <h3 class="mb-0 text-white"><?php echo $shipmentCount; ?></h3>
                                        </div>
                                        <div class="mini-stat-icon">
                                            <i class="ri-ship-line"></i>
                                        </div>
                                    </div>
                                    <div class="mt-3">
                                        <a href="customer_shipments.php?customer=<?php echo $customer_id; ?>" class="text-white-50 d-flex align-items-center">
                                            View All Shipments <i class="ri-arrow-right-line ms-1"></i>
                                        </a>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="card mini-stat-card bg-gradient-success text-white">
                                <div class="card-body">
                                    <div class="d-flex align-items-center">
                                        <div class="flex-grow-1">
                                            <h6 class="text-white-50">Total Invoices</h6>
                                            <h3 class="mb-0 text-white"><?php echo $customer['invoices_count']; ?></h3>
                                        </div>
                                        <div class="mini-stat-icon">
                                            <i class="ri-file-list-3-line"></i>
                                        </div>
                                    </div>
                                    <div class="mt-3">
                                        <a href="customer_invoices.php?customer=<?php echo $customer_id; ?>" class="text-white-50 d-flex align-items-center">
                                            View All Invoices <i class="ri-arrow-right-line ms-1"></i>
                                        </a>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="card mini-stat-card bg-gradient-info text-white">
                                <div class="card-body">
                                    <div class="d-flex align-items-center">
                                        <div class="flex-grow-1">
                                            <h6 class="text-white-50">Outstanding Balance</h6>
                                            <h3 class="mb-0 text-white">
                                                <?php 
                                                if ($debtResult->num_rows > 0) {
                                                    echo $debtData['currency'] . ' ' . number_format($debtData['total_debt'], 2);
                                                } else {
                                                    echo '$0.00';
                                                }
                                                ?>
                                            </h3>
                                        </div>
                                        <div class="mini-stat-icon">
                                            <i class="ri-wallet-3-line"></i>
                                        </div>
                                    </div>
                                    <div class="mt-3">
                                        <a href="customer_transactions.php?customer=<?php echo $customer_id; ?>" class="text-white-50 d-flex align-items-center">
                                            View Transactions <i class="ri-arrow-right-line ms-1"></i>
                                        </a>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <!-- Customer Details -->
                        <div class="col-xl-4 col-lg-6">
                            <div class="card">
                                <div class="card-header">
                                    <div class="d-flex align-items-center">
                                        <h5 class="card-title mb-0 flex-grow-1">
                                            <i class="ri-user-3-line text-primary me-1"></i> Customer Information
                                        </h5>
                                        <div class="flex-shrink-0">
                                            <a href="edit_customer.php?id=<?php echo $customer_id; ?>" class="btn btn-soft-primary btn-sm">
                                                <i class="ri-pencil-line"></i>
                                            </a>
                                        </div>
                                    </div>
                                </div>
                                <div class="card-body">
                                    <div class="table-responsive">
                                        <table class="table table-borderless mb-0">
                                            <tbody>
                                                <tr>
                                                    <th class="ps-0" scope="row">
                                                        <div class="d-flex align-items-center">
                                                            <i class="ri-user-3-line text-primary me-2"></i> Full Name
                                                        </div>
                                                    </th>
                                                    <td class="text-muted"><?php echo htmlspecialchars($customerName); ?></td>
                                                </tr>
                                                <?php if(!empty($customer['email'])): ?>
                                                <tr>
                                                    <th class="ps-0" scope="row">
                                                        <div class="d-flex align-items-center">
                                                            <i class="ri-mail-line text-primary me-2"></i> Email
                                                        </div>
                                                    </th>
                                                    <td class="text-muted">
                                                        <a href="mailto:<?php echo htmlspecialchars($customer['email']); ?>" class="text-reset text-decoration-underline">
                                                            <?php echo htmlspecialchars($customer['email']); ?>
                                                        </a>
                                                    </td>
                                                </tr>
                                                <?php endif; ?>
                                                <?php if(!empty($customer['phone_number'])): ?>
                                                <tr>
                                                    <th class="ps-0" scope="row">
                                                        <div class="d-flex align-items-center">
                                                            <i class="ri-phone-line text-primary me-2"></i> Phone
                                                        </div>
                                                    </th>
                                                    <td class="text-muted">
                                                        <a href="tel:<?php echo htmlspecialchars($customer['phone_number']); ?>" class="text-reset text-decoration-underline">
                                                            <?php echo htmlspecialchars($customer['phone_number']); ?>
                                                        </a>
                                                    </td>
                                                </tr>
                                                <?php endif; ?>
                                                <?php if(!empty($customer['address'])): ?>
                                                <tr>
                                                    <th class="ps-0" scope="row">
                                                        <div class="d-flex align-items-center">
                                                            <i class="ri-map-pin-line text-primary me-2"></i> Address
                                                        </div>
                                                    </th>
                                                    <td class="text-muted">
                                                        <?php echo nl2br(htmlspecialchars($customer['address'])); ?>
                                                    </td>
                                                </tr>
                                                <?php endif; ?>
                                                <?php if(!empty($customer['city']) || !empty($customer['postal_code'])): ?>
                                                <tr>
                                                    <th class="ps-0" scope="row">
                                                        <div class="d-flex align-items-center">
                                                            <i class="ri-building-line text-primary me-2"></i> City/Postal
                                                        </div>
                                                    </th>
                                                    <td class="text-muted">
                                                        <?php 
                                                        echo htmlspecialchars($customer['city'] ?: ''); 
                                                        if (!empty($customer['city']) && !empty($customer['postal_code'])) {
                                                            echo ', ';
                                                        }
                                                        echo htmlspecialchars($customer['postal_code'] ?: '');
                                                        ?>
                                                    </td>
                                                </tr>
                                                <?php endif; ?>
                                                <?php if(!empty($customer['country'])): ?>
                                                <tr>
                                                    <th class="ps-0" scope="row">
                                                        <div class="d-flex align-items-center">
                                                            <i class="ri-earth-line text-primary me-2"></i> Country
                                                        </div>
                                                    </th>
                                                    <td class="text-muted"><?php echo htmlspecialchars($customer['country']); ?></td>
                                                </tr>
                                                <?php endif; ?>
                                                <tr>
                                                    <th class="ps-0" scope="row">
                                                        <div class="d-flex align-items-center">
                                                            <i class="ri-calendar-line text-primary me-2"></i> Customer ID
                                                        </div>
                                                    </th>
                                                    <td class="text-muted">#<?php echo $customer['customer_id']; ?></td>
                                                </tr>
                                            </tbody>
                                        </table>
                                    </div>
                                    <?php if($debtResult->num_rows > 0 && !empty($debtData['credit_limit'])): ?>
                                    <div class="mt-4">
                                        <h6 class="text-muted text-uppercase fs-12 mb-3">Credit Limit Usage</h6>
                                        <?php 
                                        $percentUsed = ($debtData['total_debt'] / $debtData['credit_limit']) * 100;
                                        $percentUsed = min($percentUsed, 100); // Cap at 100%
                                        
                                        // Determine progress bar color
                                        $barColor = 'bg-success';
                                        if ($percentUsed > 70) {
                                            $barColor = 'bg-danger';
                                        } else if ($percentUsed > 50) {
                                            $barColor = 'bg-warning';
                                        }
                                        ?>
                                        <div class="progress animated-progress custom-progress progress-label">
                                            <div class="progress-bar <?php echo $barColor; ?>" role="progressbar" style="width: <?php echo $percentUsed; ?>%" aria-valuenow="<?php echo $percentUsed; ?>" aria-valuemin="0" aria-valuemax="100">
                                                <div class="label"><?php echo round($percentUsed); ?>%</div>
                                            </div>
                                        </div>
                                        <div class="d-flex justify-content-between mt-2">
                                            <small><?php echo $debtData['currency'] . ' ' . number_format($debtData['total_debt'], 2); ?> used</small>
                                            <small>Limit: <?php echo $debtData['currency'] . ' ' . number_format($debtData['credit_limit'], 2); ?></small>
                                        </div>
                                    </div>
                                    <?php endif; ?>
                                </div>
                            </div>

                            <!-- Quick Actions -->
                            <div class="card">
                                <div class="card-header">
                                    <h5 class="card-title mb-0">
                                        <i class="ri-flashlight-line text-primary me-1"></i> Quick Actions
                                    </h5>
                                </div>
                                <div class="card-body">
                                    <div class="d-flex flex-wrap gap-2">
                                        <a href="file_list.php?customer=<?php echo $customer_id; ?>" class="btn btn-soft-primary">
                                            <i class="ri-ship-line me-1"></i> New Shipment
                                        </a>
                                        <a href="new_invoice.php?customer=<?php echo $customer_id; ?>" class="btn btn-soft-success">
                                            <i class="ri-file-list-3-line me-1"></i> Create Invoice
                                        </a>
                                        <a href="send_email.php?customer=<?php echo $customer_id; ?>" class="btn btn-soft-info">
                                            <i class="ri-mail-send-line me-1"></i> Send Email
                                        </a>
                                        <!--<a href="add_note.php?customer=<?php echo $customer_id; ?>" class="btn btn-soft-warning">
                                            <i class="ri-sticky-note-line me-1"></i> Add Note
                                        </a> -->
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Recent Shipments/Files -->
                        <div class="col-xl-4 col-lg-6">
                            <div class="card">
                                <div class="card-header">
                                    <div class="d-flex align-items-center">
                                        <h5 class="card-title mb-0 flex-grow-1">
                                            <i class="ri-ship-line text-primary me-1"></i> Recent Shipments
                                        </h5>
                                        <div class="flex-shrink-0">
                                            <a href="customer_shipments.php?customer=<?php echo $customer_id; ?>" class="btn btn-link btn-sm">View All <i class="ri-arrow-right-line"></i></a>
                                        </div>
                                    </div>
                                </div>
                                <div class="card-body p-0">
                                    <?php if ($recentShipments->num_rows > 0): ?>
                                        <div class="list-group list-group-flush">
                                            <?php while ($shipment = $recentShipments->fetch_assoc()): 
                                                // Determine shipment type and status
                                                $shipmentType = ($shipment['type'] == 1) ? "Local" : "Transit";
                                                $shipmentClass = ($shipment['type'] == 1) ? "file-card-local" : "file-card-transit";
                                                
                                                // Check if shipment is closed
                                                if ($shipment['close_file'] == 'Yes') {
                                                    $shipmentClass = "file-card-closed";
                                                }
                                                
                                                // Format the date
                                                $shipmentDate = new DateTime($shipment['created_date']);
                                                $formattedDate = $shipmentDate->format('M d, Y');
                                            ?>
                                            <div class="list-group-item list-group-item-action file-card <?php echo $shipmentClass; ?> p-3">
                                                <div class="d-flex align-items-center">
                                                    <div class="flex-shrink-0 me-3">
                                                        <div class="avatar-xs">
                                                            <div class="avatar-title rounded-circle bg-soft-primary text-primary">
                                                                <?php if ($shipment['type'] == 1): ?>
                                                                    <i class="ri-truck-line"></i>
                                                                <?php else: ?>
                                                                    <i class="ri-ship-line"></i>
                                                                <?php endif; ?>
                                                            </div>
                                                        </div>
                                                    </div>
                                                    <div class="flex-grow-1 overflow-hidden">
                                                        <h6 class="mb-1 text-truncate">
                                                            <a href="view_shipment.php?file_number=<?php echo urlencode($shipment['file_number']); ?>" class="text-body">
                                                                <?php echo htmlspecialchars($shipment['file_number']); ?>
                                                            </a>
                                                        </h6>
                                                        <p class="text-muted mb-0 fs-12">
                                                            <i class="ri-map-pin-line me-1"></i> Destination: <?php echo htmlspecialchars($shipment['destination']); ?>
                                                        </p>
                                                    </div>
                                                    <div class="flex-shrink-0 ms-2">
                                                        <div class="d-flex gap-1 align-items-center">
                                                            <div>
                                                                <?php if ($shipment['close_file'] == 'Yes'): ?>
                                                                    <span class="badge badge-soft-danger">Closed</span>
                                                                <?php else: ?>
                                                                    <span class="badge badge-soft-primary"><?php echo $shipmentType; ?></span>
                                                                <?php endif; ?>
                                                            </div>
                                                            <small class="text-muted"><?php echo $formattedDate; ?></small>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                            <?php endwhile; ?>
                                        </div>
                                    <?php else: ?>
                                        <div class="py-4 text-center">
                                            <div class="avatar-md mx-auto mb-4">
                                                <div class="avatar-title bg-light text-secondary rounded-circle">
                                                    <i class="ri-ship-line fs-24"></i>
                                                </div>
                                            </div>
                                            <h5>No Shipments Found</h5>
                                            <p class="text-muted mb-4">This customer has no shipment records yet.</p>
                                            <a href="file_list.php" class="btn btn-soft-primary">
                                                <i class="ri-add-line me-1"></i> Create New Shipment
                                            </a>
                                        </div>
                                    <?php endif; ?>
                                </div>
                            </div>

                            <!-- Customer Activity Timeline -->
                            <div class="card">
                                <div class="card-header">
                                    <h5 class="card-title mb-0">
                                        <i class="ri-history-line text-primary me-1"></i> Recent Activity
                                    </h5>
                                </div>
                                <div class="card-body">
                                    <div class="activity-timeline">
                                        <?php
                                        // Query for recent activity - you can customize this based on your database structure
                                        $activityQuery = "SELECT 'shipment' as type, file_number as reference, created_date as date, 'New shipment created' as description 
                                                         FROM files 
                                                         WHERE customer = ? 
                                                         UNION 
                                                         SELECT 'invoice' as type, invoice_number as reference, issue_date as date, 'Invoice issued' as description 
                                                         FROM invoices 
                                                         WHERE customer_id = ? 
                                                         ORDER BY date DESC LIMIT 5";
                                        
                                        $activityStmt = $conn->prepare($activityQuery);
                                        $activityStmt->bind_param("ii", $customer_id, $customer_id);
                                        $activityStmt->execute();
                                        $activities = $activityStmt->get_result();
                                        
                                        if ($activities->num_rows > 0):
                                            while ($activity = $activities->fetch_assoc()):
                                                // Format date
                                                $activityDate = new DateTime($activity['date']);
                                                $formattedActivityDate = $activityDate->format('M d, Y');
                                                
                                                // Set icon and color based on activity type
                                                $iconClass = 'ri-ship-line';
                                                $iconBg = 'bg-primary';
                                                if ($activity['type'] == 'invoice') {
                                                    $iconClass = 'ri-file-list-3-line';
                                                    $iconBg = 'bg-success';
                                                }
                                        ?>
                                        <div class="activity-item">
                                            <div class="activity-icon <?php echo $iconBg; ?> text-white">
                                                <i class="<?php echo $iconClass; ?>"></i>
                                            </div>
                                            <div class="ms-3 pt-1">
                                                <h6 class="mb-1"><?php echo htmlspecialchars($activity['description']); ?></h6>
                                                <p class="text-muted mb-1">
                                                    Ref: <?php echo htmlspecialchars($activity['reference']); ?>
                                                </p>
                                                <small class="text-muted"><?php echo $formattedActivityDate; ?></small>
                                            </div>
                                        </div>
                                        <?php 
                                            endwhile;
                                        else:
                                        ?>
                                        <div class="text-center py-4">
                                            <div class="avatar-sm mx-auto mb-3">
                                                <div class="avatar-title bg-light text-secondary rounded-circle">
                                                    <i class="ri-history-line fs-20"></i>
                                                </div>
                                            </div>
                                            <h6>No Recent Activity</h6>
                                            <p class="text-muted mb-0">No recent activity recorded for this customer.</p>
                                        </div>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Financial Data and Notes -->
                        <div class="col-xl-4 col-lg-12">
                            <!-- Financial Information -->
                            <div class="card">
                                <div class="card-header">
                                    <div class="d-flex align-items-center">
                                        <h5 class="card-title mb-0 flex-grow-1">
                                            <i class="ri-money-dollar-circle-line text-primary me-1"></i> Financial Information
                                        </h5>
                                        <div class="flex-shrink-0">
                                            <a href="customer_transactions.php?customer=<?php echo $customer_id; ?>" class="btn btn-link btn-sm">View All <i class="ri-arrow-right-line"></i></a>
                                        </div>
                                    </div>
                                </div>
                                <div class="card-body">
                                    <?php
                                    // Query for the financial summary
                                    $financialQuery = "SELECT 
                                                      SUM(CASE WHEN transaction_type = 'invoice' THEN amount ELSE 0 END) as total_invoiced,
                                                      SUM(CASE WHEN transaction_type = 'payment' THEN amount ELSE 0 END) as total_paid
                                                      FROM debt_transactions 
                                                      WHERE customer_id = ?";
                                    $financialStmt = $conn->prepare($financialQuery);
                                    
                                    if ($financialStmt) {
                                        $financialStmt->bind_param("i", $customer_id);
                                        $financialStmt->execute();
                                        $financialResult = $financialStmt->get_result();
                                        $financialData = $financialResult->fetch_assoc();
                                    } else {
                                        $financialData = [
                                            'total_invoiced' => 0,
                                            'total_paid' => 0
                                        ];
                                    }
                                    
                                    $totalInvoiced = $financialData['total_invoiced'] ?? 0;
                                    $totalPaid = $financialData['total_paid'] ?? 0;
                                    $balance = $totalInvoiced - $totalPaid;
                                    $currency = ($debtResult->num_rows > 0) ? $debtData['currency'] : '$';
                                    ?>
                                    
                                    <div class="row g-0 mb-3">
                                        <div class="col-4 border-end">
                                            <div class="text-center p-3">
                                                <h5 class="mb-0"><?php echo $currency . ' ' . number_format($totalInvoiced, 2); ?></h5>
                                                <p class="text-muted mb-0">Invoiced</p>
                                            </div>
                                        </div>
                                        <div class="col-4 border-end">
                                            <div class="text-center p-3">
                                                <h5 class="mb-0"><?php echo $currency . ' ' . number_format($totalPaid, 2); ?></h5>
                                                <p class="text-muted mb-0">Paid</p>
                                            </div>
                                        </div>
                                        <div class="col-4">
                                            <div class="text-center p-3">
                                                <h5 class="mb-0"><?php echo $currency . ' ' . number_format($balance, 2); ?></h5>
                                                <p class="text-muted mb-0">Balance</p>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <!-- Recent Transactions -->
                                    <?php
                                    $transactionQuery = "SELECT transaction_id, transaction_date, amount, transaction_type, reference_id
                                                        FROM debt_transactions 
                                                        WHERE customer_id = ? 
                                                        ORDER BY transaction_date DESC LIMIT 4";
                                    $transactionStmt = $conn->prepare($transactionQuery);
                                    
                                    if ($transactionStmt) {
                                        $transactionStmt->bind_param("i", $customer_id);
                                        $transactionStmt->execute();
                                        $transactions = $transactionStmt->get_result();
                                    
                                        if ($transactions->num_rows > 0):
                                    ?>
                                    <h6 class="text-uppercase text-muted mt-4 mb-3 fs-13">Recent Transactions</h6>
                                    <div class="table-responsive">
                                        <table class="table table-borderless table-sm mb-0">
                                            <thead class="text-muted fs-13">
                                                <tr>
                                                    <th>Date</th>
                                                    <th>Type</th>
                                                    <th class="text-end">Amount</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php while ($transaction = $transactions->fetch_assoc()): 
                                                    $transactionDate = new DateTime($transaction['transaction_date']);
                                                    $formattedTransDate = $transactionDate->format('M d, Y');
                                                    
                                                    // Set type label and class
                                                    $typeLabel = ucfirst($transaction['transaction_type']);
                                                    $typeClass = 'text-danger';
                                                    
                                                    if ($transaction['transaction_type'] == 'payment') {
                                                        $typeClass = 'text-success';
                                                    }
                                                ?>
                                                <tr>
                                                    <td class="fw-medium"><?php echo $formattedTransDate; ?></td>
                                                    <td><span class="badge badge-soft-<?php echo ($transaction['transaction_type'] == 'payment') ? 'success' : 'danger'; ?>"><?php echo $typeLabel; ?></span></td>
                                                    <td class="text-end <?php echo $typeClass; ?>"><?php echo $currency . ' ' . number_format($transaction['amount'], 2); ?></td>
                                                </tr>
                                                <?php endwhile; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                    <?php else: ?>
                                    <div class="text-center py-4 mt-3">
                                        <div class="avatar-sm mx-auto mb-3">
                                            <div class="avatar-title bg-light text-secondary rounded-circle">
                                                <i class="ri-exchange-dollar-line fs-20"></i>
                                            </div>
                                        </div>
                                        <h6>No Transactions</h6>
                                        <p class="text-muted mb-0">No financial transactions found for this customer.</p>
                                    </div>
                                    <?php 
                                        endif;
                                    }
                                    ?>
                                </div>
                            </div>
                            
                            <!-- Customer Tags and Notes -->
                            <div class="card">
                                <div class="card-header d-flex align-items-center">
                                    <h5 class="card-title mb-0 flex-grow-1">
                                        <i class="ri-price-tag-3-line text-primary me-1"></i> Tags & Notes
                                    </h5>
                                    <div class="flex-shrink-0">
                                        <button type="button" class="btn btn-soft-primary btn-sm" data-bs-toggle="modal" data-bs-target="#addTagModal">
                                            <i class="ri-add-line"></i> Add Tag
                                        </button>
                                    </div>
                                </div>
                                <div class="card-body">
                                    <div class="d-flex flex-wrap gap-2 mb-4">
                                        <span class="customer-tag"><i class="ri-price-tag-3-line me-1"></i> VIP Client</span>
                                        <span class="customer-tag"><i class="ri-price-tag-3-line me-1"></i> Regular Shipper</span>
                                        <span class="customer-tag"><i class="ri-price-tag-3-line me-1"></i> <?php echo htmlspecialchars($customer['country'] ?: 'International'); ?></span>
                                        <span class="customer-tag"><i class="ri-price-tag-3-line me-1"></i> Credit Terms</span>
                                    </div>
                                    
                                    <!--
                                    <div class="mt-4">
                                        <h6 class="text-uppercase text-muted fs-13 mb-3">Notes</h6>
                                        
                                        
                                        <div class="mb-3">
                                            <div class="d-flex mb-3">
                                                <div class="flex-shrink-0">
                                                    <img src="assets/images/users/avatar-1.jpg" alt="" class="avatar-xs rounded-circle">
                                                </div>
                                                <div class="ms-3">
                                                    <h6 class="fs-14 mb-1">Admin</h6>
                                                    <p class="text-muted mb-0">Added on Mar 04, 2025</p>
                                                </div>
                                            </div>
                                            <p class="text-muted">Customer requires special handling for containerized cargo. Always notify them 3 days before shipment arrival.</p>
                                        </div>
                                        
                                        <div>
                                            <div class="d-flex mb-3">
                                                <div class="flex-shrink-0">
                                                    <img src="assets/images/users/avatar-3.jpg" alt="" class="avatar-xs rounded-circle">
                                                </div>
                                                <div class="ms-3">
                                                    <h6 class="fs-14 mb-1">Karim</h6>
                                                    <p class="text-muted mb-0">Added on Feb 15, 2025</p>
                                                </div>
                                            </div>
                                            <p class="text-muted">They prefer communication via WhatsApp. New contact person added: John at +123456789</p>
                                        </div>
                                        
                                        
                                        <div class="mt-4">
                                            <textarea class="form-control" rows="3" placeholder="Add a note about this customer..."></textarea>
                                            <div class="text-end mt-2">
                                                <button type="button" class="btn btn-soft-primary btn-sm" id="addNoteBtn">
                                                    <i class="ri-add-line align-middle me-1"></i> Add Note
                                                </button>
                                            </div>
                                        </div>
                                    </div>  -->
                                </div>
                            </div>
                        </div>
                    </div><!--end row-->
                    
                    <!-- Add Tag Modal -->
                    <div class="modal fade" id="addTagModal" tabindex="-1" aria-labelledby="addTagModalLabel" aria-hidden="true">
                        <div class="modal-dialog modal-dialog-centered">
                            <div class="modal-content">
                                <div class="modal-header">
                                    <h5 class="modal-title" id="addTagModalLabel">Add Tag to Customer</h5>
                                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                                </div>
                                <div class="modal-body">
                                    <form>
                                        <div class="mb-3">
                                            <label for="tagName" class="form-label">Tag Name</label>
                                            <input type="text" class="form-control" id="tagName" placeholder="Enter tag name">
                                        </div>
                                        <div class="mb-3">
                                            <label class="form-label d-block mb-3">Select Tag Color</label>
                                            <div class="d-flex flex-wrap gap-2">
                                                <div class="form-check">
                                                    <input type="radio" id="tagColorBlue" name="tagColor" class="form-check-input" checked>
                                                    <label class="form-check-label" for="tagColorBlue">
                                                        <span class="badge bg-primary">Blue</span>
                                                    </label>
                                                </div>
                                                <div class="form-check">
                                                    <input type="radio" id="tagColorGreen" name="tagColor" class="form-check-input">
                                                    <label class="form-check-label" for="tagColorGreen">
                                                        <span class="badge bg-success">Green</span>
                                                    </label>
                                                </div>
                                                <div class="form-check">
                                                    <input type="radio" id="tagColorRed" name="tagColor" class="form-check-input">
                                                    <label class="form-check-label" for="tagColorRed">
                                                        <span class="badge bg-danger">Red</span>
                                                    </label>
                                                </div>
                                                <div class="form-check">
                                                    <input type="radio" id="tagColorYellow" name="tagColor" class="form-check-input">
                                                    <label class="form-check-label" for="tagColorYellow">
                                                        <span class="badge bg-warning">Yellow</span>
                                                    </label>
                                                </div>
                                                <div class="form-check">
                                                    <input type="radio" id="tagColorPurple" name="tagColor" class="form-check-input">
                                                    <label class="form-check-label" for="tagColorPurple">
                                                        <span class="badge bg-purple">Purple</span>
                                                    </label>
                                                </div>
                                            </div>
                                        </div>
                                    </form>
                                </div>
                                <div class="modal-footer">
                                    <button type="button" class="btn btn-light" data-bs-dismiss="modal">Cancel</button>
                                    <button type="button" class="btn btn-primary" id="addTagBtn">Add Tag</button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <!-- Additional Plugins -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet">
    <script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
    
    <!-- Chart.js for future implementation -->
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    
    <script>
    document.addEventListener('DOMContentLoaded', function() {
        // Initialize any select2 dropdowns
        if(typeof $.fn.select2 !== 'undefined') {
            $('.select2').select2();
        }
        
        // Animation for stat cards
        const statCards = document.querySelectorAll('.mini-stat-card');
        statCards.forEach(card => {
            card.addEventListener('mouseenter', function() {
                this.classList.add('shadow-lg');
            });
            card.addEventListener('mouseleave', function() {
                this.classList.remove('shadow-lg');
            });
        });
        
        // Initialize tooltips
        var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'))
        var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
            return new bootstrap.Tooltip(tooltipTriggerEl)
        });
        
        // Add event listeners for buttons
        document.getElementById('addTagBtn').addEventListener('click', addNewTag);
        document.getElementById('addNoteBtn').addEventListener('click', addNewNote);
    });
    
    function deactivateCustomer() {
        Swal.fire({
            title: 'Are you sure?',
            text: "Do you want to deactivate this customer?",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonText: 'Yes, deactivate it!',
            cancelButtonText: 'No, cancel!',
            confirmButtonClass: 'btn btn-primary w-xs me-2 mt-2',
            cancelButtonClass: 'btn btn-danger w-xs mt-2',
            buttonsStyling: false,
            showCloseButton: true
        }).then(function(result) {
            if (result.value) {
                window.location.href = "change_customer_status.php?id=<?php echo $customer_id; ?>&status=0";
            }
        });
    }
    
    function activateCustomer() {
        Swal.fire({
            title: 'Are you sure?',
            text: "Do you want to activate this customer?",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonText: 'Yes, activate it!',
            cancelButtonText: 'No, cancel!',
            confirmButtonClass: 'btn btn-primary w-xs me-2 mt-2',
            cancelButtonClass: 'btn btn-danger w-xs mt-2',
            buttonsStyling: false,
            showCloseButton: true
        }).then(function(result) {
            if (result.value) {
                window.location.href = "change_customer_status.php?id=<?php echo $customer_id; ?>&status=1";
            }
        });
    }
    
    // Function to add a new tag
    function addNewTag() {
        const tagName = document.getElementById('tagName').value;
        if (!tagName) {
            Swal.fire({
                title: 'Error!',
                text: 'Please enter a tag name',
                icon: 'error',
                confirmButtonClass: 'btn btn-primary w-xs mt-2',
                buttonsStyling: false
            });
            return;
        }
        
        // Get selected color
        let tagColor = 'bg-primary';
        document.querySelectorAll('input[name="tagColor"]').forEach(input => {
            if (input.checked) {
                tagColor = input.nextElementSibling.querySelector('.badge').classList[1];
            }
        });
        
        // AJAX call to save the tag
        $.ajax({
            url: 'add_customer_tag.php',
            type: 'POST',
            data: {
                customer_id: <?php echo $customer_id; ?>,
                tag_name: tagName,
                tag_color: tagColor
            },
            success: function(response) {
                // Parse response
                try {
                    const data = JSON.parse(response);
                    if(data.success) {
                        Swal.fire({
                            title: 'Success!',
                            text: 'Tag added successfully',
                            icon: 'success',
                            confirmButtonClass: 'btn btn-primary w-xs mt-2',
                            buttonsStyling: false
                        }).then(() => {
                            // Refresh the page to show the new tag
                            location.reload();
                        });
                    } else {
                        Swal.fire({
                            title: 'Error!',
                            text: data.message || 'Failed to add tag',
                            icon: 'error',
                            confirmButtonClass: 'btn btn-primary w-xs mt-2',
                            buttonsStyling: false
                        });
                    }
                } catch(e) {
                    Swal.fire({
                        title: 'Error!',
                        text: 'An unexpected error occurred',
                        icon: 'error',
                        confirmButtonClass: 'btn btn-primary w-xs mt-2',
                        buttonsStyling: false
                    });
                }
            },
            error: function() {
                Swal.fire({
                    title: 'Error!',
                    text: 'Failed to communicate with the server',
                    icon: 'error',
                    confirmButtonClass: 'btn btn-primary w-xs mt-2',
                    buttonsStyling: false
                });
            }
        });
        
        // Close the modal
        $('#addTagModal').modal('hide');
    }
    
    // Function to submit a new note
    function addNewNote() {
        const noteText = document.querySelector('textarea[placeholder="Add a note about this customer..."]').value;
        if (!noteText) {
            Swal.fire({
                title: 'Error!',
                text: 'Please enter a note',
                icon: 'error',
                confirmButtonClass: 'btn btn-primary w-xs mt-2',
                buttonsStyling: false
            });
            return;
        }
        
        // AJAX call to save the note
        $.ajax({
            url: 'add_customer_note.php',
            type: 'POST',
            data: {
                customer_id: <?php echo $customer_id; ?>,
                note_text: noteText
            },
            success: function(response) {
                // Parse response
                try {
                    const data = JSON.parse(response);
                    if(data.success) {
                        Swal.fire({
                            title: 'Success!',
                            text: 'Note added successfully',
                            icon: 'success',
                            confirmButtonClass: 'btn btn-primary w-xs mt-2',
                            buttonsStyling: false
                        }).then(() => {
                            // Refresh the page to show the new note
                            location.reload();
                        });
                    } else {
                        Swal.fire({
                            title: 'Error!',
                            text: data.message || 'Failed to add note',
                            icon: 'error',
                            confirmButtonClass: 'btn btn-primary w-xs mt-2',
                            buttonsStyling: false
                        });
                    }
                } catch(e) {
                    Swal.fire({
                        title: 'Error!',
                        text: 'An unexpected error occurred',
                        icon: 'error',
                        confirmButtonClass: 'btn btn-primary w-xs mt-2',
                        buttonsStyling: false
                    });
                }
            },
            error: function() {
                Swal.fire({
                    title: 'Error!',
                    text: 'Failed to communicate with the server',
                    icon: 'error',
                    confirmButtonClass: 'btn btn-primary w-xs mt-2',
                    buttonsStyling: false
                });
            }
        });
        
        // Clear the textarea
        document.querySelector('textarea[placeholder="Add a note about this customer..."]').value = '';
    }
    </script>

    <script src="assets/js/app.js"></script>
</body>
</html>