<?php
session_start();
include_once('includes/config.php');
if (!isset($_SESSION['uid'])) {
    header('location:logout.php');
    exit();
}

$userId = $_SESSION['uid'];
$userType = $_SESSION['usertype'];

// Set default period to 30 days
$defaultPeriod = 30;
$selectedPeriod = isset($_GET['period']) ? (int)$_GET['period'] : $defaultPeriod;
$customFromDate = isset($_GET['custom_from']) ? $_GET['custom_from'] : '';
$customToDate = isset($_GET['custom_to']) ? $_GET['custom_to'] : '';
$selectedArea = isset($_GET['area']) ? $_GET['area'] : '';

// Calculate cutoff date
if ($customFromDate && $customToDate) {
    $cutoffDate = $customFromDate;
    $endDate = $customToDate;
    $periodText = "Custom Range: " . date('M j, Y', strtotime($customFromDate)) . " to " . date('M j, Y', strtotime($customToDate));
} else {
    $cutoffDate = date('Y-m-d', strtotime("-{$selectedPeriod} days"));
    $endDate = date('Y-m-d');
    $periodText = $selectedPeriod . " days";
}

// Get customers who haven't had sales in the specified period
$query = "SELECT 
    c.ID,
    c.CustomerName,
    c.Mobile,
    c.AlternativePhone,
    c.Address,
    c.Area,
    c.CustomerType,
    c.CreatedDate,
    COALESCE(MAX(ps.SaleDate), 'Never') as LastSaleDate,
    COALESCE(DATEDIFF(NOW(), MAX(ps.SaleDate)), 999) as DaysSinceLastSale,
    COUNT(ps.ID) as TotalSales,
    COALESCE(SUM(ps.TotalAmount), 0) as TotalAmount
FROM tblcustomers c
LEFT JOIN tblpossales ps ON c.ID = ps.CustomerID 
WHERE c.IsActive = 1";

$params = [];
$paramTypes = '';

// Add area filter if specified
if (!empty($selectedArea)) {
    $query .= " AND c.Area = ?";
    $params[] = $selectedArea;
    $paramTypes .= 's';
}

$query .= " GROUP BY c.ID
HAVING (MAX(ps.SaleDate) IS NULL OR MAX(ps.SaleDate) < ?)
ORDER BY DaysSinceLastSale DESC, c.CustomerName ASC";

$params[] = $cutoffDate;
$paramTypes .= 's';

$stmt = mysqli_prepare($con, $query);
if (!empty($paramTypes)) {
    mysqli_stmt_bind_param($stmt, $paramTypes, ...$params);
}
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);

// Get statistics by counting the same results as our main query
$totalInactive = mysqli_num_rows($result);

// Get total customers count
$totalCustomersQuery = "SELECT COUNT(*) as total FROM tblcustomers c WHERE c.IsActive = 1" . 
                       (!empty($selectedArea) ? " AND c.Area = '$selectedArea'" : "");
$totalCustomersResult = mysqli_query($con, $totalCustomersQuery);
$totalCustomersCount = mysqli_fetch_assoc($totalCustomersResult)['total'];

// Get customers who never made a purchase
$neverPurchasedQuery = "SELECT COUNT(DISTINCT c.ID) as total 
                        FROM tblcustomers c 
                        LEFT JOIN tblpossales ps ON c.ID = ps.CustomerID 
                        WHERE c.IsActive = 1 AND ps.CustomerID IS NULL" .
                        (!empty($selectedArea) ? " AND c.Area = '$selectedArea'" : "");
$neverPurchasedResult = mysqli_query($con, $neverPurchasedQuery);
$neverPurchasedCount = mysqli_fetch_assoc($neverPurchasedResult)['total'];

// Get all areas for filter
$areasQuery = "SELECT DISTINCT Area FROM tblcustomers WHERE IsActive = 1 AND Area IS NOT NULL AND Area != '' ORDER BY Area";
$areasResult = mysqli_query($con, $areasQuery);
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Inactive Customer Report | Mariyappa Nadar Ricemill</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <link href="vendor/fontawesome-free/css/all.min.css" rel="stylesheet">
    <link href="css/sb-admin-2.min.css" rel="stylesheet">
    <link href="vendor/datatables/dataTables.bootstrap4.min.css" rel="stylesheet">
    
    <style>
        /* Modern design similar to complaints-management-modern.php */
        body { 
            background: #f8f9fa;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
        }
        
        .main-header {
            background: linear-gradient(135deg, #1a1a2e 0%, #16213e 50%, #0f4c75 100%);
            color: white;
            padding: 12px 0;
            margin-bottom: 20px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        
        .header-content {
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 10px;
        }
        
        .header-title {
            display: flex;
            align-items: center;
            gap: 10px;
            margin: 0;
            font-size: 18px;
            font-weight: 600;
        }
        
        .stats-card {
            background: white;
            border-radius: 10px;
            padding: 20px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            border-left: 4px solid #e74c3c;
            transition: transform 0.2s;
        }
        
        .stats-card:hover {
            transform: translateY(-2px);
        }
        
        .filter-card {
            background: white;
            border-radius: 10px;
            padding: 20px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            margin-bottom: 20px;
        }
        
        .period-btn {
            margin: 5px;
            min-width: 100px;
            border-radius: 20px;
            font-weight: 500;
        }
        
        .period-btn.active {
            background: linear-gradient(45deg, #667eea, #764ba2);
            border-color: #667eea;
            color: white;
        }
        
        .customer-card {
            background: white;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 10px;
            box-shadow: 0 1px 5px rgba(0,0,0,0.1);
            transition: all 0.3s ease;
            border-left: 4px solid #dc3545;
        }
        
        .customer-card:hover {
            transform: translateX(5px);
            box-shadow: 0 3px 15px rgba(0,0,0,0.15);
        }
        
        .never-purchased {
            border-left-color: #6c757d;
        }
        
        .long-inactive {
            border-left-color: #dc3545;
        }
        
        .badge-status {
            font-size: 0.75rem;
            padding: 4px 8px;
            border-radius: 12px;
        }
        
        .table-modern {
            background: white;
            border-radius: 10px;
            overflow: hidden;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        
        .table-modern th {
            background: linear-gradient(45deg, #667eea, #764ba2);
            color: white;
            border: none;
            font-weight: 600;
            text-transform: uppercase;
            font-size: 0.8rem;
            letter-spacing: 0.5px;
        }
        
        .export-section {
            background: white;
            padding: 15px;
            border-radius: 8px;
            box-shadow: 0 1px 5px rgba(0,0,0,0.1);
            margin-bottom: 20px;
        }
        
        .modal-header-custom {
            background: linear-gradient(45deg, #667eea, #764ba2);
            color: white;
            border-radius: 10px 10px 0 0;
        }
        
        .filter-option-btn {
            height: 80px;
            border-radius: 8px;
            border: 2px solid #e3e6f0;
            background: white;
            transition: all 0.3s ease;
        }
        
        .filter-option-btn:hover {
            border-color: #667eea;
            background: #f8f9ff;
            transform: translateY(-2px);
        }
        
        .filter-option-btn.active {
            background: linear-gradient(45deg, #667eea, #764ba2);
            border-color: #667eea;
            color: white;
        }
        
        /* Compact Grid List Styles - Similar to Transaction History */
        .customer-list {
            list-style: none;
            padding: 0;
            margin: 0;
        }
        
        .customer-item {
            display: flex;
            align-items: center;
            gap: 12px;
            padding: 16px 20px;
            border-bottom: 1px solid rgba(0, 0, 0, 0.04);
            transition: all 0.2s ease;
            cursor: pointer;
            background: rgba(255, 255, 255, 0.95);
        }
        
        .customer-item:hover {
            background: rgba(103, 126, 234, 0.02);
            transform: translateY(-1px);
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }
        
        .customer-item:last-child {
            border-bottom: none;
        }
        
        .customer-icon {
            width: 40px;
            height: 40px;
            border-radius: 12px;
            display: flex;
            align-items: center;
            justify-content: center;
            color: #fff;
            font-size: 16px;
            flex-shrink: 0;
        }
        
        .customer-icon.retail {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            box-shadow: 0 4px 12px rgba(103, 126, 234, 0.3);
        }
        
        .customer-icon.wholesale {
            background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
            box-shadow: 0 4px 12px rgba(245, 87, 108, 0.3);
        }
        
        .customer-main {
            flex: 1;
            min-width: 0;
        }
        
        .customer-name {
            font-weight: 600;
            font-size: 14px;
            color: #1a1a1a;
            margin-bottom: 2px;
            display: flex;
            align-items: center;
            gap: 8px;
        }
        
        .customer-type {
            font-size: 10px;
            background: linear-gradient(135deg, rgba(103, 126, 234, 0.1), rgba(118, 75, 162, 0.1));
            color: #667eea;
            padding: 2px 6px;
            border-radius: 8px;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }
        
        .customer-details {
            font-size: 12px;
            color: #6b7280;
            line-height: 1.3;
            display: flex;
            flex-wrap: wrap;
            gap: 8px;
        }
        
        .contact-info, .area-info, .last-sale {
            display: flex;
            align-items: center;
            gap: 3px;
        }
        
        .contact-info i, .area-info i {
            font-size: 10px;
            opacity: 0.7;
        }
        
        .last-sale.never {
            color: #ef4444;
            font-weight: 600;
        }
        
        .customer-stats {
            display: flex;
            flex-direction: column;
            align-items: flex-end;
            gap: 4px;
            flex-shrink: 0;
            min-width: 80px;
        }
        
        .days-inactive {
            font-weight: 700;
            font-size: 14px;
            padding: 4px 8px;
            border-radius: 6px;
            text-align: center;
            min-width: 70px;
        }
        
        .days-inactive.normal {
            background: rgba(16, 185, 129, 0.1);
            color: #10b981;
            border: 1px solid rgba(16, 185, 129, 0.2);
        }
        
        .days-inactive.warning {
            background: rgba(245, 158, 11, 0.1);
            color: #f59e0b;
            border: 1px solid rgba(245, 158, 11, 0.2);
        }
        
        .days-inactive.critical {
            background: rgba(239, 68, 68, 0.1);
            color: #ef4444;
            border: 1px solid rgba(239, 68, 68, 0.2);
        }
        
        .sales-amount {
            font-weight: 600;
            font-size: 13px;
            color: #1a1a1a;
            text-align: right;
        }
        
        .sales-amount small {
            font-size: 10px;
            color: #6b7280;
            display: block;
            margin-top: 2px;
        }
        
        .customer-actions {
            display: flex;
            gap: 4px;
            flex-shrink: 0;
        }
        
        .action-btn {
            width: 32px;
            height: 32px;
            border: none;
            border-radius: 8px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 12px;
            cursor: pointer;
            transition: all 0.2s ease;
        }
        
        .call-btn {
            background: rgba(16, 185, 129, 0.1);
            color: #10b981;
        }
        
        .call-btn:hover {
            background: rgba(16, 185, 129, 0.2);
            transform: scale(1.1);
        }
        
        .view-btn {
            background: rgba(103, 126, 234, 0.1);
            color: #667eea;
        }
        
        .view-btn:hover {
            background: rgba(103, 126, 234, 0.2);
            transform: scale(1.1);
        }
        
        .edit-btn {
            background: rgba(245, 158, 11, 0.1);
            color: #f59e0b;
        }
        
        .edit-btn:hover {
            background: rgba(245, 158, 11, 0.2);
            transform: scale(1.1);
        }
        
        .empty-state {
            text-align: center;
            color: #6b7280;
            padding: 48px 24px;
            font-size: 16px;
        }
        
        .empty-state i {
            font-size: 48px;
            margin-bottom: 16px;
            display: block;
            opacity: 0.5;
            color: #10b981;
        }
        
        .empty-title {
            font-size: 18px;
            font-weight: 600;
            color: #1a1a1a;
            margin-bottom: 8px;
        }
        
        .empty-subtitle {
            font-size: 14px;
            color: #6b7280;
        }
        
        /* Mobile optimizations */
        @media (max-width: 768px) {
            .customer-item {
                padding: 14px 16px;
                gap: 10px;
            }
            
            .customer-icon {
                width: 36px;
                height: 36px;
                font-size: 14px;
            }
            
            .customer-name {
                font-size: 13px;
                flex-direction: column;
                align-items: flex-start;
                gap: 4px;
            }
            
            .customer-details {
                font-size: 11px;
                flex-direction: column;
                gap: 2px;
            }
            
            .customer-stats {
                min-width: 60px;
            }
            
            .days-inactive {
                font-size: 12px;
                min-width: 60px;
            }
            
            .sales-amount {
                font-size: 12px;
            }
            
            .action-btn {
                width: 28px;
                height: 28px;
                font-size: 11px;
            }
        }
        
        @media (max-width: 480px) {
            .customer-item {
                flex-direction: column;
                align-items: flex-start;
                gap: 8px;
                padding: 12px 16px;
            }
            
            .customer-main {
                width: 100%;
            }
            
            .customer-stats {
                align-self: flex-end;
                flex-direction: row;
                align-items: center;
                gap: 12px;
            }
            
            .customer-actions {
                align-self: flex-end;
            }
        }
    </style>
</head>

<body id="page-top">
    <div id="wrapper">
        <?php include_once('includes/sidebar.php');?>
        
        <div id="content-wrapper" class="d-flex flex-column">
            <div id="content">
                <?php include_once('includes/topbar.php');?>
                
                <!-- Main Header -->
                <div class="main-header">
                    <div class="container-fluid">
                        <div class="header-content">
                            <h1 class="header-title">
                                <i class="fas fa-user-clock"></i>
                                Inactive Customer Report
                                <span class="badge badge-light ml-2"><?php echo $totalInactive; ?> customers</span>
                            </h1>
                            <div class="header-actions">
                                <button class="btn btn-light btn-sm" data-toggle="modal" data-target="#filterModal">
                                    <i class="fas fa-filter mr-2"></i>Filters
                                </button>
                                <button class="btn btn-success btn-sm" onclick="exportToExcel()">
                                    <i class="fas fa-download mr-2"></i>Export
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
                
                <div class="container-fluid">
                    
                    <!-- Quick Stats -->
                    <div class="row mb-4">
                        <div class="col-xl-3 col-md-6 mb-4">
                            <div class="stats-card">
                                <div class="d-flex align-items-center">
                                    <div class="mr-3">
                                        <i class="fas fa-user-times fa-2x text-danger"></i>
                                    </div>
                                    <div>
                                        <div class="h4 mb-0 font-weight-bold text-gray-800"><?php echo $totalInactive; ?></div>
                                        <div class="text-xs font-weight-bold text-uppercase text-muted">Inactive Customers</div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="col-xl-3 col-md-6 mb-4">
                            <div class="stats-card">
                                <div class="d-flex align-items-center">
                                    <div class="mr-3">
                                        <i class="fas fa-calendar-alt fa-2x text-warning"></i>
                                    </div>
                                    <div>
                                        <div class="h4 mb-0 font-weight-bold text-gray-800"><?php echo $selectedPeriod; ?></div>
                                        <div class="text-xs font-weight-bold text-uppercase text-muted">Days Period</div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="col-xl-3 col-md-6 mb-4">
                            <div class="stats-card">
                                <div class="d-flex align-items-center">
                                    <div class="mr-3">
                                        <i class="fas fa-map-marker-alt fa-2x text-info"></i>
                                    </div>
                                    <div>
                                        <div class="h4 mb-0 font-weight-bold text-gray-800">
                                            <?php echo $selectedArea ? htmlspecialchars($selectedArea) : 'All Areas'; ?>
                                        </div>
                                        <div class="text-xs font-weight-bold text-uppercase text-muted">Area Filter</div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="col-xl-3 col-md-6 mb-4">
                            <div class="stats-card">
                                <div class="d-flex align-items-center">
                                    <div class="mr-3">
                                        <i class="fas fa-clock fa-2x text-primary"></i>
                                    </div>
                                    <div>
                                        <div class="h4 mb-0 font-weight-bold text-gray-800"><?php echo date('M j, Y'); ?></div>
                                        <div class="text-xs font-weight-bold text-uppercase text-muted">Report Date</div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Current Filter Info -->
                    <div class="filter-card">
                        <div class="row align-items-center">
                            <div class="col-md-6">
                                <h6 class="mb-1">
                                    <i class="fas fa-filter mr-2 text-primary"></i>Current Filter
                                </h6>
                                <p class="mb-0 text-muted">
                                    Showing customers with no sales activity for <strong><?php echo $periodText; ?></strong>
                                    <?php if ($selectedArea): ?>
                                    in area <strong><?php echo htmlspecialchars($selectedArea); ?></strong>
                                    <?php endif; ?>
                                </p>
                            </div>
                            <div class="col-md-6 text-right">
                                <small class="text-muted">
                                    Cutoff Date: <strong><?php echo date('M j, Y', strtotime($cutoffDate)); ?></strong>
                                </small>
                            </div>
                        </div>
                    </div>

                    <!-- Inactive Customers Table -->
                    <div class="card shadow table-modern">
                        <div class="card-header py-3 d-flex flex-row align-items-center justify-content-between">
                            <h6 class="m-0 font-weight-bold text-white">
                                <i class="fas fa-list mr-2"></i>Inactive Customers Details
                            </h6>
                            <div class="dropdown no-arrow">
                                <a class="dropdown-toggle text-white" href="#" role="button" data-toggle="dropdown">
                                    <i class="fas fa-ellipsis-v fa-sm fa-fw text-gray-400"></i>
                                </a>
                                <div class="dropdown-menu dropdown-menu-right shadow">
                                    <a class="dropdown-item" href="#" onclick="toggleView('table')">
                                        <i class="fas fa-table fa-sm fa-fw mr-2 text-gray-400"></i>Table View
                                    </a>
                                    <a class="dropdown-item" href="#" onclick="toggleView('cards')">
                                        <i class="fas fa-th-large fa-sm fa-fw mr-2 text-gray-400"></i>Card View
                                    </a>
                                </div>
                            </div>
                        </div>
                        <div class="card-body p-0">
                            
                            <!-- Compact Grid View like Transaction History -->
                            <div id="compactView">
                                <ul class="customer-list">
                                    <?php if ($result && mysqli_num_rows($result) > 0): ?>
                                        <?php while ($customer = mysqli_fetch_assoc($result)): ?>
                                            <li class="customer-item" onclick="viewCustomerDetails(<?php echo $customer['ID']; ?>)">
                                                <div class="customer-icon <?php echo strtolower($customer['CustomerType']); ?>">
                                                    <i class="fas <?php echo $customer['CustomerType'] == 'Retail' ? 'fa-user' : 'fa-store'; ?>"></i>
                                                </div>
                                                <div class="customer-main">
                                                    <div class="customer-name">
                                                        <?php echo htmlspecialchars($customer['CustomerName']); ?>
                                                        <span class="customer-type"><?php echo $customer['CustomerType']; ?></span>
                                                    </div>
                                                    <div class="customer-details">
                                                        <?php if (!empty($customer['Mobile'])): ?>
                                                            <span class="contact-info">
                                                                <i class="fas fa-phone"></i> <?php echo htmlspecialchars($customer['Mobile']); ?>
                                                            </span>
                                                        <?php endif; ?>
                                                        <span class="area-info">
                                                            <i class="fas fa-map-marker-alt"></i> <?php echo htmlspecialchars($customer['Area']); ?>
                                                        </span>
                                                        <?php if ($customer['LastSaleDate'] !== 'Never'): ?>
                                                            <span class="last-sale">
                                                                Last sale: <?php echo date('M j, Y', strtotime($customer['LastSaleDate'])); ?>
                                                            </span>
                                                        <?php else: ?>
                                                            <span class="last-sale never">Never purchased</span>
                                                        <?php endif; ?>
                                                    </div>
                                                </div>
                                                <div class="customer-stats">
                                                    <div class="days-inactive <?php echo $customer['DaysSinceLastSale'] > 180 ? 'critical' : ($customer['DaysSinceLastSale'] > 90 ? 'warning' : 'normal'); ?>">
                                                        <?php echo $customer['DaysSinceLastSale'] == 999 ? '∞' : $customer['DaysSinceLastSale']; ?> days
                                                    </div>
                                                    <div class="sales-amount">
                                                        ₹<?php echo number_format($customer['TotalAmount'], 0); ?>
                                                        <small>(<?php echo $customer['TotalSales']; ?> sales)</small>
                                                    </div>
                                                </div>
                                                <div class="customer-actions" onclick="event.stopPropagation()">
                                                    <?php if (!empty($customer['Mobile'])): ?>
                                                        <button class="action-btn call-btn" onclick="contactCustomer('<?php echo htmlspecialchars($customer['Mobile']); ?>')" title="Call Customer">
                                                            <i class="fas fa-phone"></i>
                                                        </button>
                                                    <?php endif; ?>
                                                    <button class="action-btn view-btn" onclick="window.location.href='customer-ledger.php?customer_id=<?php echo $customer['ID']; ?>'" title="View Ledger">
                                                        <i class="fas fa-file-invoice"></i>
                                                    </button>
                                                    <button class="action-btn edit-btn" onclick="window.location.href='customer-management.php?edit=<?php echo $customer['ID']; ?>'" title="Edit Customer">
                                                        <i class="fas fa-edit"></i>
                                                    </button>
                                                </div>
                                            </li>
                                        <?php endwhile; ?>
                                    <?php else: ?>
                                        <li class="empty-state">
                                            <i class="fas fa-smile"></i>
                                            <div class="empty-title">Great News!</div>
                                            <div class="empty-subtitle">No inactive customers found for the selected period.</div>
                                        </li>
                                    <?php endif; ?>
                                </ul>
                            </div>
                            
                        </div>
                    </div>
                </div>
            </div>
            
            <?php include_once('includes/footer.php');?>
        </div>
    </div>

    <!-- Filter Modal -->
    <div class="modal fade" id="filterModal" tabindex="-1" role="dialog">
        <div class="modal-dialog modal-lg" role="document">
            <div class="modal-content">
                <div class="modal-header modal-header-custom">
                    <h5 class="modal-title">
                        <i class="fas fa-filter mr-2"></i>Filter Inactive Customers
                    </h5>
                    <button type="button" class="close text-white" data-dismiss="modal">
                        <span>&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <div class="text-center mb-4">
                        <p class="text-muted">Select a time period to find inactive customers</p>
                    </div>
                    
                    <form id="filterForm" method="GET">
                        <div class="row">
                            <div class="col-6 mb-3">
                                <button type="button" class="btn filter-option-btn w-100 <?php echo $selectedPeriod == 7 ? 'active' : ''; ?>" 
                                        onclick="setPeriod(7)">
                                    <i class="fas fa-calendar-week mb-2"></i><br>
                                    <span>1 Week</span>
                                </button>
                            </div>
                            <div class="col-6 mb-3">
                                <button type="button" class="btn filter-option-btn w-100 <?php echo $selectedPeriod == 14 ? 'active' : ''; ?>" 
                                        onclick="setPeriod(14)">
                                    <i class="fas fa-calendar-alt mb-2"></i><br>
                                    <span>2 Weeks</span>
                                </button>
                            </div>
                            <div class="col-6 mb-3">
                                <button type="button" class="btn filter-option-btn w-100 <?php echo $selectedPeriod == 30 ? 'active' : ''; ?>" 
                                        onclick="setPeriod(30)">
                                    <i class="fas fa-calendar mb-2"></i><br>
                                    <span>1 Month</span>
                                </button>
                            </div>
                            <div class="col-6 mb-3">
                                <button type="button" class="btn filter-option-btn w-100 <?php echo $selectedPeriod == 60 ? 'active' : ''; ?>" 
                                        onclick="setPeriod(60)">
                                    <i class="fas fa-calendar-times mb-2"></i><br>
                                    <span>2 Months</span>
                                </button>
                            </div>
                            <div class="col-6 mb-3">
                                <button type="button" class="btn filter-option-btn w-100 <?php echo $selectedPeriod == 90 ? 'active' : ''; ?>" 
                                        onclick="setPeriod(90)">
                                    <i class="fas fa-calendar-minus mb-2"></i><br>
                                    <span>3 Months</span>
                                </button>
                            </div>
                            <div class="col-6 mb-3">
                                <button type="button" class="btn filter-option-btn w-100 <?php echo $selectedPeriod == 180 ? 'active' : ''; ?>" 
                                        onclick="setPeriod(180)">
                                    <i class="fas fa-calendar-check mb-2"></i><br>
                                    <span>6 Months</span>
                                </button>
                            </div>
                        </div>
                        
                        <hr>
                        
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label>Area Filter</label>
                                    <select class="form-control" name="area">
                                        <option value="">All Areas</option>
                                        <?php if ($areasResult): ?>
                                            <?php while($area = mysqli_fetch_assoc($areasResult)): ?>
                                                <option value="<?php echo htmlspecialchars($area['Area']); ?>" 
                                                        <?php echo $selectedArea == $area['Area'] ? 'selected' : ''; ?>>
                                                    <?php echo htmlspecialchars($area['Area']); ?>
                                                </option>
                                            <?php endwhile; ?>
                                        <?php endif; ?>
                                    </select>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label>Quick Actions</label><br>
                                    <button type="button" class="btn btn-outline-primary btn-sm mr-2" onclick="resetFilters()">
                                        <i class="fas fa-undo mr-1"></i>Reset All
                                    </button>
                                    <button type="button" class="btn btn-success btn-sm" onclick="applyFilters()">
                                        <i class="fas fa-search mr-1"></i>Apply
                                    </button>
                                </div>
                            </div>
                        </div>
                        
                        <hr>
                        
                        <div class="row">
                            <div class="col-12">
                                <h6 class="mb-3">Custom Date Range</h6>
                                <div class="row">
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label>From Date</label>
                                            <input type="date" class="form-control" name="custom_from" 
                                                   value="<?php echo $customFromDate; ?>">
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="form-group">
                                            <label>To Date</label>
                                            <input type="date" class="form-control" name="custom_to" 
                                                   value="<?php echo $customToDate; ?>">
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <input type="hidden" name="period" id="selectedPeriod" value="<?php echo $selectedPeriod; ?>">
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                    <button type="button" class="btn btn-primary" onclick="applyFilters()">
                        <i class="fas fa-search mr-2"></i>Apply Filters
                    </button>
                </div>
            </div>
        </div>
    </div>

    <?php include_once('includes/footer2.php');?>

    <!-- Scripts -->
    <script src="vendor/jquery/jquery.min.js"></script>
    <script src="vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
    <script src="vendor/jquery-easing/jquery.easing.min.js"></script>
    <script src="js/sb-admin-2.min.js"></script>
    <script src="vendor/datatables/jquery.dataTables.min.js"></script>
    <script src="vendor/datatables/dataTables.bootstrap4.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.18.5/xlsx.full.min.js"></script>

    <script>
        let currentPeriod = <?php echo $selectedPeriod; ?>;
        
        $(document).ready(function() {
            // Initialize DataTable
            $('#inactiveCustomersTable').DataTable({
                "pageLength": 25,
                "responsive": true,
                "order": [[5, "desc"]], // Sort by Days Inactive descending
                "columnDefs": [
                    { "orderable": false, "targets": [8] } // Disable sorting on Actions column
                ],
                "language": {
                    "lengthMenu": "Show _MENU_ customers per page",
                    "zeroRecords": "No inactive customers found",
                    "info": "Showing _START_ to _END_ of _TOTAL_ inactive customers",
                    "infoEmpty": "No customers available",
                    "search": "Search customers:",
                    "paginate": {
                        "first": "First",
                        "last": "Last",
                        "next": "Next",
                        "previous": "Previous"
                    }
                }
            });
        });
        
        function setPeriod(days) {
            currentPeriod = days;
            document.getElementById('selectedPeriod').value = days;
            
            // Update button states
            document.querySelectorAll('.filter-option-btn').forEach(btn => {
                btn.classList.remove('active');
            });
            event.target.closest('.filter-option-btn').classList.add('active');
        }
        
        function applyFilters() {
            document.getElementById('filterForm').submit();
        }
        
        function resetFilters() {
            window.location.href = 'customer-inactive-report.php';
        }
        
        function contactCustomer(phoneNumber) {
            if (phoneNumber) {
                // Open phone dialer
                window.location.href = 'tel:' + phoneNumber;
            } else {
                alert('No phone number available for this customer.');
            }
        }
        
        function viewCustomerDetails(customerId) {
            // Redirect to customer ledger or management page
            window.location.href = 'customer-ledger.php?customer_id=' + customerId;
        }
        
        function exportToExcel() {
            // Get table data
            const table = document.getElementById('inactiveCustomersTable');
            const wb = XLSX.utils.book_new();
            
            // Convert table to worksheet
            const ws = XLSX.utils.table_to_sheet(table, {
                raw: false,
                dateNF: 'yyyy-mm-dd'
            });
            
            // Set column widths
            ws['!cols'] = [
                { width: 5 },   // #
                { width: 25 },  // Customer
                { width: 20 },  // Contact
                { width: 15 },  // Area
                { width: 15 },  // Last Sale
                { width: 12 },  // Days Inactive
                { width: 15 },  // Total Sales
                { width: 12 },  // Status
                { width: 10 }   // Actions (will be empty)
            ];
            
            XLSX.utils.book_append_sheet(wb, ws, 'Inactive Customers');
            
            // Generate filename with current date
            const now = new Date();
            const filename = `Inactive_Customers_Report_${now.getFullYear()}-${String(now.getMonth()+1).padStart(2,'0')}-${String(now.getDate()).padStart(2,'0')}.xlsx`;
            
            // Save file
            XLSX.writeFile(wb, filename);
        }
        
        // Auto-dismiss alerts
        setTimeout(function() {
            $('.alert').fadeOut();
        }, 5000);
    </script>
</body>
</html>