<?php
// Enable error reporting for debugging
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('log_errors', 1);
ini_set('error_log', __DIR__ . '/error.log');

session_start();

// Check if config file exists
if (!file_exists('includes/config.php')) {
    die('Error: config.php file not found');
}

include_once('includes/config.php');

// Check database connection
if (!isset($con) || !$con) {
    die('Error: Database connection not established');
}

if (!isset($_SESSION['uid'])) {
    header('location:logout.php');
    exit();
}

$area = isset($_GET['area']) ? trim($_GET['area']) : '';
$customerType = isset($_GET['type']) ? trim($_GET['type']) : 'Retail';

// Validate customer type
if (!in_array($customerType, ['Retail', 'Shop'])) {
    $customerType = 'Retail';
}

// Validate area parameter
if (empty($area)) {
    error_log('Area parameter is empty, redirecting to customer-areas.php');
    header('location: customer-areas.php?type=' . urlencode($customerType));
    exit();
}

// Log the parameters for debugging
error_log("area-customers.php called with area: '$area', type: '$customerType'");

// Get customers in the area with outstanding amounts and nearby customer information
// Using MySQL 5.7 compatible query without window functions
$customersQuery = "
    SELECT 
        c.ID,
        c.CustomerName,
        c.Mobile,
        c.AlternativePhone,
        c.Area,
        c.Address,
        c.CustomerType,
        c.CreatedDate,
        c.NearbyCustomerId,
        nc.CustomerName as NearbyCustomerName,
        COALESCE(SUM(CASE WHEN p.TransactionType = 'Credit' THEN p.Amount ELSE 0 END), 0) as TotalCredit,
        COALESCE(SUM(CASE WHEN p.TransactionType = 'Debit' THEN p.Amount ELSE 0 END), 0) as TotalDebit,
        (COALESCE(SUM(CASE WHEN p.TransactionType = 'Debit' THEN p.Amount ELSE 0 END), 0) - 
         COALESCE(SUM(CASE WHEN p.TransactionType = 'Credit' THEN p.Amount ELSE 0 END), 0)) as OutstandingAmount
    FROM tblcustomers c
    LEFT JOIN tblcustomers nc ON c.NearbyCustomerId = nc.ID
    LEFT JOIN tblcustomerpayments p ON c.ID = p.CustomerID AND p.IsActive = 1
    WHERE c.Area = ? AND c.CustomerType = ? AND c.IsActive = 1 
    GROUP BY c.ID, c.CustomerName, c.Mobile, c.AlternativePhone, c.Area, c.Address, c.CustomerType, c.CreatedDate, c.NearbyCustomerId, nc.CustomerName
    ORDER BY 
        CASE 
            WHEN c.NearbyCustomerId IS NULL THEN c.CustomerName
            ELSE nc.CustomerName
        END,
        c.NearbyCustomerId IS NOT NULL,
        c.CustomerName
";

// Add comprehensive error handling for the database query
try {
    error_log("Preparing customer query for area: '$area', type: '$customerType'");
    
    $stmt = mysqli_prepare($con, $customersQuery);
    if (!$stmt) {
        throw new Exception('Prepare failed: ' . mysqli_error($con));
    }
    
    $bindResult = mysqli_stmt_bind_param($stmt, "ss", $area, $customerType);
    if (!$bindResult) {
        throw new Exception('Bind param failed: ' . mysqli_stmt_error($stmt));
    }
    
    $executeResult = mysqli_stmt_execute($stmt);
    if (!$executeResult) {
        throw new Exception('Execute failed: ' . mysqli_stmt_error($stmt));
    }
    
    $customersResult = mysqli_stmt_get_result($stmt);
    if (!$customersResult) {
        throw new Exception('Get result failed: ' . mysqli_stmt_error($stmt));
    }
    
    error_log("Customer query executed successfully");
    
    // Get latest reminders for each customer (MySQL 5.7 compatible)
    $reminderQuery = "
        SELECT 
            r1.CustomerID,
            r1.ReminderDate,
            r1.ReminderText,
            r1.IsCompleted
        FROM tblcustomerreminders r1
        INNER JOIN (
            SELECT CustomerID, MAX(ReminderDate) as MaxDate
            FROM tblcustomerreminders
            GROUP BY CustomerID
        ) r2 ON r1.CustomerID = r2.CustomerID AND r1.ReminderDate = r2.MaxDate
    ";
    
    $reminderResult = mysqli_query($con, $reminderQuery);
    $reminders = array();
    if ($reminderResult) {
        while ($row = mysqli_fetch_assoc($reminderResult)) {
            $reminders[$row['CustomerID']] = $row;
        }
    }
    
} catch (Exception $e) {
    error_log('Database query error in area-customers.php: ' . $e->getMessage());
    die('Database query failed: ' . htmlspecialchars($e->getMessage()));
}

// Get customer count and outstanding summary
$customerCount = mysqli_num_rows($customersResult);
error_log("Found $customerCount customers for area '$area'");

// Calculate summary statistics
$totalOutstanding = 0;
$totalAdvance = 0;
$outstandingCustomers = 0;
$advanceCustomers = 0;

// Reset result pointer to calculate statistics
try {
    mysqli_data_seek($customersResult, 0);
    while ($row = mysqli_fetch_assoc($customersResult)) {
        $outstanding = floatval($row['OutstandingAmount'] ?? 0);
        if ($outstanding > 0) {
            $totalOutstanding += $outstanding;
            $outstandingCustomers++;
        } elseif ($outstanding < 0) {
            $totalAdvance += abs($outstanding);
            $advanceCustomers++;
        }
    }
    
    // Reset result pointer for main loop
    mysqli_data_seek($customersResult, 0);
    error_log("Statistics calculated successfully");
    
} catch (Exception $e) {
    error_log('Error calculating statistics: ' . $e->getMessage());
    // Continue execution even if statistics fail
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Mariyappa Nadar Ricemill | <?php echo htmlspecialchars($area); ?> - <?php echo $customerType; ?> Customers</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" type="text/css">
    <link href="css/sb-admin-2.min.css" rel="stylesheet">
    <style>
        /* Full-height layout to utilize viewport height */
        html, body, #wrapper, #content-wrapper, #content {
            height: 100%;
        }

        /* Compact global paddings */
        .container-fluid {
            padding: 8px 10px;
        }

        .customer-card {
            background: white;
            border-radius: 8px;
            box-shadow: 0 1px 4px rgba(0,0,0,0.1);
            transition: all 0.2s ease;
            border: 1px solid #e8e8e8;
            margin-bottom: 8px;
            overflow: hidden;
        }
        
        .customer-card:hover {
            transform: translateY(-1px);
            box-shadow: 0 4px 12px rgba(0,0,0,0.15);
        }
        
        .customer-card-header {
            background: linear-gradient(135deg, #4e73df 0%, #224abe 100%);
            color: white;
            padding: 8px 10px;
            position: relative;
            display: flex;
            align-items: center;
            gap: 10px;
        }
        
    .customer-avatar {
            width: 32px;
            height: 32px;
            background: rgba(255,255,255,0.2);
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 0.9rem;
            border: 1px solid rgba(255,255,255,0.3);
            flex-shrink: 0;
        }
        
        .customer-header-info {
            flex: 1;
            min-width: 0;
        }
        
        .customer-name {
            font-size: 0.9rem;
            font-weight: 600;
            margin-bottom: 2px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }
        
        .customer-type-badge {
            background: rgba(255,255,255,0.2);
            padding: 1px 6px;
            border-radius: 10px;
            font-size: 0.65rem;
            display: inline-block;
        }
        
        .customer-card-body {
            padding: 8px 10px;
        }
        
        .customer-info {
            margin-bottom: 6px;
        }
        
        .info-item {
            display: flex;
            align-items: center;
            margin-bottom: 4px;
            font-size: 0.78rem;
        }
        
        .info-item i {
            width: 14px;
            color: #6c757d;
            margin-right: 8px;
            font-size: 0.75rem;
        }
        
        .info-item .value {
            color: #495057;
            flex: 1;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }
        
        .outstanding-amount {
            background: linear-gradient(135deg, #e74c3c 0%, #c0392b 100%);
            color: white;
            padding: 4px 8px;
            border-radius: 12px;
            font-size: 0.75rem;
            font-weight: 600;
            display: inline-block;
            margin-top: 4px;
            min-width: 60px;
            text-align: center;
        }
        
        .outstanding-amount.advance {
            background: linear-gradient(135deg, #27ae60 0%, #229954 100%);
        }
        
        .outstanding-amount.zero {
            background: linear-gradient(135deg, #95a5a6 0%, #7f8c8d 100%);
        }
        
        .reminder-info {
            background: linear-gradient(135deg, #3498db 0%, #2980b9 100%);
            color: white;
            padding: 4px 8px;
            border-radius: 12px;
            font-size: 0.70rem;
            font-weight: 600;
            display: inline-block;
            margin-top: 4px;
            min-width: 60px;
            text-align: center;
        }
        
        .reminder-info.pending {
            background: linear-gradient(135deg, #f39c12 0%, #e67e22 100%);
        }
        
        .reminder-info.completed {
            background: linear-gradient(135deg, #27ae60 0%, #229954 100%);
        }
        
        .reminder-info.overdue {
            background: linear-gradient(135deg, #e74c3c 0%, #c0392b 100%);
            animation: pulse 2s infinite;
        }
        
        @keyframes pulse {
            0% { opacity: 1; }
            50% { opacity: 0.7; }
            100% { opacity: 1; }
        }
        
        /* Nearby customer styling */
        .nearby-customer-indicator {
            background: linear-gradient(135deg, #17a2b8 0%, #138496 100%);
            color: white;
            padding: 2px 6px;
            border-radius: 10px;
            font-size: 0.65rem;
            display: inline-block;
            margin-left: 4px;
        }
        
        .customer-card.has-nearby {
            border-left: 3px solid #17a2b8;
        }
        
        .nearby-group {
            margin-bottom: 1rem;
            padding: 0.5rem;
            background: rgba(23, 162, 184, 0.05);
            border-radius: 8px;
            border-left: 3px solid #17a2b8;
        }
        
        .nearby-group-header {
            font-size: 0.85rem;
            font-weight: 600;
            color: #17a2b8;
            margin-bottom: 0.5rem;
            padding-left: 0.5rem;
        }
        
        .customer-actions {
            border-top: 1px solid #f0f0f0;
            padding: 6px 8px;
            background: #fafafa;
            display: flex;
            gap: 6px;
        }
        
        .pos-btn {
            background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
            color: white;
            border: none;
            border-radius: 6px;
            padding: 6px 10px;
            font-weight: 600;
            font-size: 0.78rem;
            transition: all 0.2s ease;
            flex: 1;
            text-decoration: none;
            text-align: center;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 6px;
        }
        
        .pos-btn:hover {
            background: linear-gradient(135deg, #218838 0%, #1e7e34 100%);
            color: white;
            text-decoration: none;
            transform: translateY(-1px);
        }
        
        .details-btn {
            background: #6c757d;
            color: white;
            border: none;
            border-radius: 6px;
            padding: 6px 8px;
            font-size: 0.78rem;
            transition: all 0.2s ease;
            text-decoration: none;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        
        .details-btn:hover {
            background: #545b62;
            color: white;
            text-decoration: none;
            transform: translateY(-1px);
        }

        .collect-btn {
            background: linear-gradient(135deg, #ff9900 0%, #ff8c00 100%);
            color: white;
            border: none;
            border-radius: 6px;
            padding: 6px 10px;
            font-weight: 600;
            font-size: 0.78rem;
            transition: all 0.2s ease;
            flex: 1;
            text-decoration: none;
            text-align: center;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 6px;
        }
        .collect-btn:hover { filter: brightness(0.95); color: #fff; text-decoration: none; transform: translateY(-1px); }
        
        .reminder-btn {
            background: linear-gradient(135deg, #3498db 0%, #2980b9 100%);
            color: white;
            border: none;
            border-radius: 6px;
            padding: 6px 8px;
            font-size: 0.78rem;
            transition: all 0.2s ease;
            text-decoration: none;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
        }
        
        .reminder-btn:hover {
            background: linear-gradient(135deg, #2980b9 0%, #1f618d 100%);
            color: white;
            text-decoration: none;
            transform: translateY(-1px);
        }
        
        /* Dropdown styles */
        .dropdown {
            position: relative;
            display: inline-block;
        }
        
        .actions-btn {
            background: #6c757d;
            color: white;
            border: none;
            border-radius: 6px;
            padding: 8px 10px;
            font-size: 0.9rem;
            transition: all 0.2s ease;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            min-width: 32px;
            height: 32px;
        }
        
        .actions-btn:hover {
            background: #545b62;
            transform: translateY(-1px);
        }
        
        /* Action Modal Styles */
        .action-btn {
            height: 80px;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            font-size: 0.9rem;
            border-radius: 8px;
            transition: all 0.2s ease;
        }
        
        .action-btn i {
            font-size: 1.5rem;
        }
        
        .action-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(0,0,0,0.15);
        }
        
        .dropdown-menu {
            display: none;
            position: absolute;
            right: 0;
            top: 100%;
            margin-top: 5px;
            background: white;
            border: 1px solid #e3e6f0;
            border-radius: 6px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.15);
            z-index: 9999;
            min-width: 140px;
        }
        
        .dropdown-menu.show {
            display: block !important;
        }
        
        .dropdown-item {
            display: block;
            width: 100%;
            padding: 8px 12px;
            font-size: 0.75rem;
            color: #495057;
            text-decoration: none;
            border: none;
            background: none;
            text-align: left;
            cursor: pointer;
            transition: all 0.2s ease;
            border-bottom: 1px solid #f8f9fa;
        }
        
        .dropdown-item:last-child {
            border-bottom: none;
        }
        
        .dropdown-item:hover {
            background: #f8f9fc;
            color: #2e59d9;
            text-decoration: none;
        }
        
        .dropdown-item i {
            width: 16px;
            margin-right: 8px;
            text-align: center;
        }
        
        .back-btn {
            background: #6c757d;
            color: white;
            border: none;
            border-radius: 8px;
            padding: 6px 10px;
            font-weight: 500;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 8px;
            transition: all 0.2s ease;
            margin-bottom: 12px;
            font-size: 0.85rem;
        }
        
        .back-btn:hover {
            background: #545b62;
            color: white;
            text-decoration: none;
            transform: translateY(-1px);
        }
        
        .page-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 8px;
            padding: 12px 14px;
            margin-bottom: 12px;
        }
        
        .search-box {
            background: white;
            border-radius: 8px;
            padding: 8px 10px;
            margin-bottom: 10px;
            box-shadow: 0 1px 4px rgba(0,0,0,0.1);
        }
        
        .search-input {
            border: 1px solid #e0e0e0;
            border-radius: 6px;
            padding: 6px 30px 6px 10px;
            font-size: 0.85rem;
            transition: all 0.2s ease;
        }
        
        .search-input:focus {
            border-color: #4e73df;
            box-shadow: 0 0 0 2px rgba(78,115,223,0.25);
        }
        
        .search-icon {
            position: absolute;
            right: 12px;
            top: 50%;
            transform: translateY(-50%);
            color: #6c757d;
            font-size: 0.85rem;
        }
        
        /* Tighter grid gutters for compact look */
        #customersGrid {
            margin-left: -6px;
            margin-right: -6px;
        }
        #customersGrid > .col-6 {
            padding-left: 6px;
            padding-right: 6px;
        }

        @media (max-width: 768px) {
            .customer-card-body {
                padding: 8px;
            }
            
            .customer-actions {
                padding: 6px 8px;
                gap: 4px;
            }
            
            .pos-btn {
                flex: 2;
                padding: 6px 8px;
                font-size: 0.74rem;
            }
            
            .reminder-btn, .details-btn {
                flex: 1;
                padding: 6px 6px;
                font-size: 0.74rem;
            }
            
            .customer-name {
                font-size: 0.82rem;
            }
            
            .info-item {
                font-size: 0.75rem;
                margin-bottom: 4px;
            }
            
            .page-header {
                padding: 10px 12px;
            }
            
            .search-box {
                padding: 8px;
                margin-bottom: 10px;
            }

            /* Show only icons on very small screens for ultra-compact look */
            .pos-btn .btn-text { display: none; }
        }
    </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');?>
                
                <!-- Begin Page Content -->
                <div class="container-fluid">
                    
                    <!-- Back Button -->
                    <a href="customer-areas.php?type=<?php echo $customerType; ?>" class="back-btn">
                        <i class="fas fa-arrow-left"></i>
                        Back to Areas
                    </a>
                    
                    <!-- Page Header -->
                    <div class="page-header">
                        <div class="d-flex align-items-center justify-content-between">
                            <div>
                                <h1 class="h5 mb-1">
                                    <i class="fas fa-users mr-2"></i>
                                    <?php echo htmlspecialchars($area); ?> - <?php echo $customerType; ?>
                                </h1>
                                <p class="mb-0" style="font-size: 0.85rem; opacity: 0.9;">
                                    <?php echo number_format($customerCount); ?> customer<?php echo $customerCount != 1 ? 's' : ''; ?> found
                                </p>
                            </div>
                            <a href="customer-management.php" class="btn btn-light btn-sm">
                                <i class="fas fa-plus mr-1"></i>Add
                            </a>
                        </div>
                    </div>

                    <!-- Search Box -->
                    <div class="search-box">
                        <div class="position-relative">
                            <input type="text" class="form-control search-input" id="customerSearch" placeholder="Search customers, mobile, or outstanding amount...">
                            <i class="fas fa-search search-icon"></i>
                        </div>
                        <div class="mt-2 text-center">
                            <button type="button" class="btn btn-warning btn-sm mr-2" onclick="filterOutstandingCustomers()">
                                <i class="fas fa-exclamation-triangle mr-1"></i>Outstanding Only
                            </button>
                            <button type="button" class="btn btn-success btn-sm mr-2" onclick="filterAdvanceCustomers()">
                                <i class="fas fa-arrow-down mr-1"></i>Advance Only
                            </button>
                            <button type="button" class="btn btn-secondary btn-sm" onclick="showAllCustomers()">
                                <i class="fas fa-users mr-1"></i>Show All
                            </button>
                        </div>
                    </div>

                    <!-- Customers Grid -->
                    <div class="row" id="customersGrid">
                        <?php if ($customerCount > 0): ?>
                            <?php while ($customer = mysqli_fetch_assoc($customersResult)): ?>
                          <div class="col-6 customer-item" 
                              id="customer-item-<?php echo $customer['ID']; ?>"
                                     data-name="<?php echo strtolower(htmlspecialchars($customer['CustomerName'])); ?>"
                                     data-mobile="<?php echo htmlspecialchars($customer['Mobile']); ?>"
                                     data-alt-phone="<?php echo htmlspecialchars($customer['AlternativePhone'] ?? ''); ?>"
                                     data-outstanding="<?php echo $customer['OutstandingAmount']; ?>"
                                     data-nearby="<?php echo !empty($customer['NearbyCustomerId']) ? $customer['NearbyCustomerId'] : ''; ?>">
                                    <div class="customer-card <?php echo !empty($customer['NearbyCustomerId']) ? 'has-nearby' : ''; ?>">
                                        <div class="customer-card-header">
                                            <div class="customer-avatar">
                                                <i class="fas fa-user"></i>
                                            </div>
                                            <div class="customer-header-info">
                                                <div class="customer-name">
                                                    <?php echo htmlspecialchars($customer['CustomerName']); ?>
                                                    <?php if (!empty($customer['NearbyCustomerId'])): ?>
                                                        <span class="nearby-customer-indicator" title="Near <?php echo htmlspecialchars($customer['NearbyCustomerName']); ?>">
                                                            <i class="fas fa-location-arrow"></i>
                                                        </span>
                                                    <?php endif; ?>
                                                </div>
                                                <div class="customer-type-badge"><?php echo substr($customer['CustomerType'], 0, 1); ?></div>
                                            </div>
                                        </div>
                                        
                                        <div class="customer-card-body">
                                            <div class="customer-info">
                                                <div class="info-item">
                                                    <i class="fas fa-phone"></i>
                                                    <span class="value"><?php echo htmlspecialchars($customer['Mobile']); ?></span>
                                                </div>
                                                
                                                <div class="info-item">
                                                    <i class="fas fa-map-marker-alt"></i>
                                                    <span class="value"><?php echo htmlspecialchars($customer['Area']); ?></span>
                                                </div>
                                                
                                <div class="info-item">
                                    <i class="fas fa-home"></i>
                                    <span class="value"><?php echo htmlspecialchars(substr($customer['Address'], 0, 25)); ?><?php echo strlen($customer['Address']) > 25 ? '...' : ''; ?></span>
                                </div>
                                
                                <?php if (!empty($customer['NearbyCustomerId']) && !empty($customer['NearbyCustomerName'])): ?>
                                <div class="info-item">
                                    <i class="fas fa-location-arrow text-info"></i>
                                    <span class="value text-info">
                                        Near: <?php echo htmlspecialchars(substr($customer['NearbyCustomerName'], 0, 20)); ?><?php echo strlen($customer['NearbyCustomerName']) > 20 ? '...' : ''; ?>
                                    </span>
                                </div>
                                <?php endif; ?>                                                <div class="info-item">
                                                    <i class="fas fa-balance-scale"></i>
                                                    <span class="value">
                                                        <?php 
                                                        $outstandingAmount = $customer['OutstandingAmount'];
                                                        if ($outstandingAmount > 0): ?>
                                                            <span class="outstanding-amount" id="outstanding-amt-<?php echo $customer['ID']; ?>">₹<?php echo number_format($outstandingAmount, 0); ?></span>
                                                        <?php elseif ($outstandingAmount < 0): ?>
                                                            <span class="outstanding-amount advance" id="outstanding-amt-<?php echo $customer['ID']; ?>">₹<?php echo number_format(abs($outstandingAmount), 0); ?> Adv</span>
                                                        <?php else: ?>
                                                            <span class="outstanding-amount zero" id="outstanding-amt-<?php echo $customer['ID']; ?>">₹0</span>
                                                        <?php endif; ?>
                                                    </span>
                                                </div>
                                                
                                                <?php 
                                                // Get reminder for this customer from our reminders array
                                                $customerReminder = isset($reminders[$customer['ID']]) ? $reminders[$customer['ID']] : null;
                                                if ($customerReminder && !empty($customerReminder['ReminderDate'])): ?>
                                                <div class="info-item">
                                                    <i class="fas fa-bell"></i>
                                                    <span class="value">
                                                        <?php 
                                                        $reminderTimestamp = strtotime($customerReminder['ReminderDate']);
                                                        $currentTimestamp = time();
                                                        $status = $customerReminder['IsCompleted'];
                                                        
                                                        // Determine reminder status class
                                                        $reminderClass = 'reminder-info';
                                                        if ($status == 1) { // IsCompleted = 1
                                                            $reminderClass .= ' completed';
                                                        } elseif ($reminderTimestamp < $currentTimestamp && $status == 0) {
                                                            $reminderClass .= ' overdue';
                                                        } else {
                                                            $reminderClass .= ' pending';
                                                        }
                                                        
                                                        // Format the date and time for display
                                                        $displayDate = date('M j', $reminderTimestamp);
                                                        $displayTime = date('g:i A', $reminderTimestamp);
                                                        ?>
                                                        <span class="<?php echo $reminderClass; ?>">
                                                            <?php echo $displayDate; ?> <?php echo $displayTime; ?>
                                                        </span>
                                                    </span>
                                                </div>
                                                <?php endif; ?>
                                            </div>
                                        </div>
                                        
                                        <div class="customer-actions">
                                            <!-- Primary Action Buttons -->
                                            <a href="pos.php?customer_id=<?php echo $customer['ID']; ?>" class="pos-btn">
                                                <i class="fas fa-cash-register"></i><span class="btn-text">POS</span>
                                            </a>
                                            <button type="button" class="collect-btn" onclick="openPaymentCollectModal(<?php echo $customer['ID']; ?>, '<?php echo htmlspecialchars($customer['CustomerName'], ENT_QUOTES); ?>')">
                                                <i class="fas fa-rupee-sign"></i><span class="btn-text">Collect</span>
                                            </button>
                                            
                                            <!-- Actions Button -->
                                            <button class="actions-btn" onclick="openActionsModal(<?php echo $customer['ID']; ?>, '<?php echo htmlspecialchars($customer['CustomerName'], ENT_QUOTES); ?>')">
                                                <i class="fas fa-ellipsis-v"></i>
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            <?php endwhile; ?>
                        <?php else: ?>
                            <div class="col-12">
                                <div class="text-center py-4">
                                    <i class="fas fa-users fa-2x text-muted mb-2"></i>
                                    <h5 class="text-muted">No Customers Found</h5>
                                    <p class="text-muted mb-3">No <?php echo strtolower($customerType); ?> customers in <?php echo htmlspecialchars($area); ?>.</p>
                                    <a href="customer-management.php" class="btn btn-primary btn-sm">
                                        <i class="fas fa-plus mr-1"></i>Add Customer
                                    </a>
                                </div>
                            </div>
                        <?php endif; ?>
                    </div>

                </div>
                <!-- /.container-fluid -->
            </div>
            <?php include_once('includes/footer.php');?>
        </div>
    </div>
    <?php include_once('includes/footer2.php');?>

    <!-- Customer Actions Modal -->
    <div class="modal fade" id="customerActionsModal" tabindex="-1" role="dialog" aria-labelledby="customerActionsModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered" role="document">
            <div class="modal-content">
                <div class="modal-header bg-primary text-white">
                    <h5 class="modal-title" id="customerActionsModalLabel">
                        <i class="fas fa-user-cog mr-2"></i>Customer Actions
                    </h5>
                    <button type="button" class="close text-white" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <div class="text-center mb-3">
                        <h6 class="text-muted">Select an action for:</h6>
                        <h5 class="text-primary mb-3" id="actionsCustomerName"></h5>
                    </div>
                    
                    <div class="row">
                        <div class="col-6 mb-3">
                            <button type="button" class="btn btn-warning btn-block action-btn" onclick="openComplaintModalFromActions()">
                                <i class="fas fa-exclamation-triangle mb-1"></i><br>
                                <span>Complaints</span>
                            </button>
                        </div>
                        <div class="col-6 mb-3">
                            <button type="button" class="btn btn-info btn-block action-btn" onclick="openReminderModalFromActions()">
                                <i class="fas fa-bell mb-1"></i><br>
                                <span>Reminder</span>
                            </button>
                        </div>
                        <div class="col-6 mb-3">
                            <button type="button" class="btn btn-success btn-block action-btn" onclick="viewTransactionHistory()">
                                <i class="fas fa-history mb-1"></i><br>
                                <span>History</span>
                            </button>
                        </div>
                        <div class="col-6 mb-3">
                            <button type="button" class="btn btn-primary btn-block action-btn" onclick="editCustomer()">
                                <i class="fas fa-edit mb-1"></i><br>
                                <span>Edit</span>
                            </button>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">
                        <i class="fas fa-times mr-1"></i>Close
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Payment Collect Modal -->
    <div class="modal fade" id="paymentCollectModal" tabindex="-1" role="dialog" aria-labelledby="paymentCollectModalLabel" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="paymentCollectModalLabel">
                        <i class="fas fa-rupee-sign mr-2"></i>Record Payment
                    </h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <form id="paymentCollectForm">
                        <input type="hidden" id="collectCustomerId">
                        <div class="form-group">
                            <label><strong>Customer:</strong></label>
                            <p id="collectCustomerName" class="text-primary mb-2"></p>
                        </div>

                        <div class="form-group">
                            <label for="collectTransactionType">Transaction Type</label>
                            <select class="form-control" id="collectTransactionType">
                                <option value="Credit" selected>Credit (Money Received)</option>
                                <option value="Debit">Debit (Money Paid)</option>
                            </select>
                        </div>

                        <div class="form-group">
                            <label for="collectAmount">Amount (₹)</label>
                            <input type="number" class="form-control" id="collectAmount" placeholder="Enter amount" step="0.01" min="0" required>
                        </div>

                        <div class="form-group">
                            <label for="collectMethod">Payment Method</label>
                            <select class="form-control" id="collectMethod" required>
                                <option value="Cash">Cash</option>
                                <option value="UPI">UPI</option>
                                <option value="Card">Card</option>
                                <option value="Bank Transfer">Bank Transfer</option>
                                <option value="Cheque">Cheque</option>
                                <option value="Online">Online</option>
                            </select>
                        </div>

                        <div class="form-group" id="collectRefGroup" style="display:none;">
                            <label for="collectReference">Reference Number</label>
                            <input type="text" class="form-control" id="collectReference" placeholder="Enter reference/transaction number">
                        </div>

                        <div class="form-group">
                            <label for="collectDescription">Description (Optional)</label>
                            <textarea class="form-control" id="collectDescription" rows="2" placeholder="Enter payment note"></textarea>
                        </div>

                        <div class="form-group">
                            <label for="collectDate">Payment Date</label>
                            <input type="date" class="form-control" id="collectDate" required>
                        </div>
                    </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" id="collectSaveBtn" onclick="savePaymentCollect()">
                        <i class="fas fa-save mr-1"></i>Record Payment
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Reminder Modal -->
    <div class="modal fade" id="reminderModal" tabindex="-1" role="dialog" aria-labelledby="reminderModalLabel" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="reminderModalLabel">
                        <i class="fas fa-bell mr-2"></i>Add Reminder
                    </h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <form id="reminderForm">
                        <input type="hidden" id="reminderCustomerId" name="customerId">
                        
                        <div class="form-group">
                            <label for="customerNameDisplay"><strong>Customer:</strong></label>
                            <p id="customerNameDisplay" class="text-primary"></p>
                        </div>
                        
                        <div class="form-group">
                            <label for="reminderDate">Reminder Date</label>
                            <input type="date" class="form-control" id="reminderDate" name="reminderDate" required>
                        </div>
                        
                        <div class="form-group">
                            <label for="reminderHour12">Reminder Time (12-hour)</label>
                            <div class="d-flex" style="gap:8px;">
                                <select class="form-control" id="reminderHour12" style="max-width:110px;"></select>
                                <select class="form-control" id="reminderMinute" style="max-width:110px;"></select>
                                <select class="form-control" id="reminderAmPm" style="max-width:110px;">
                                    <option value="AM">AM</option>
                                    <option value="PM">PM</option>
                                </select>
                            </div>
                        </div>
                        
                        <div class="form-group">
                            <label for="reminderText">Reminder Note</label>
                            <textarea class="form-control" id="reminderText" name="reminderText" rows="3" placeholder="Enter reminder details..."></textarea>
                        </div>
                    </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="saveReminder()">
                        <i class="fas fa-save mr-1"></i>Save Reminder
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Complaints Modal -->
    <div class="modal fade" id="complaintModal" tabindex="-1" role="dialog" aria-labelledby="complaintModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="complaintModalLabel">
                        <i class="fas fa-exclamation-triangle mr-2"></i>Register Complaint
                    </h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <form id="complaintForm">
                        <input type="hidden" id="complaintCustomerId" name="customer_id">
                        
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="complaintCustomerName">Customer Name</label>
                                    <input type="text" class="form-control" id="complaintCustomerName" readonly>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="complaintType">Complaint Type</label>
                                    <select class="form-control" id="complaintType" name="complaint_type" required>
                                        <option value="Quality">Quality Issue</option>
                                        <option value="Quantity">Quantity Issue</option>
                                        <option value="Packaging">Packaging Issue</option>
                                        <option value="Delivery">Delivery Issue</option>
                                        <option value="Other">Other</option>
                                    </select>
                                </div>
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="complaintRiceBag">Rice Bag Product</label>
                                    <select class="form-control" id="complaintRiceBag" name="rice_bag_id" required>
                                        <option value="">Select Rice Bag Product</option>
                                        <!-- Options will be loaded dynamically -->
                                    </select>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="complaintPriority">Priority</label>
                                    <select class="form-control" id="complaintPriority" name="priority" required>
                                        <option value="Low">Low</option>
                                        <option value="Medium" selected>Medium</option>
                                        <option value="High">High</option>
                                        <option value="Critical">Critical</option>
                                    </select>
                                </div>
                            </div>
                        </div>
                        
                        <div class="form-group">
                            <label for="complaintTitle">Complaint Title</label>
                            <input type="text" class="form-control" id="complaintTitle" name="complaint_title" 
                                   placeholder="Brief description of the issue" required maxlength="200">
                        </div>
                        
                        <div class="form-group">
                            <label for="complaintDescription">Complaint Details</label>
                            <textarea class="form-control" id="complaintDescription" name="complaint_description" 
                                      rows="4" placeholder="Provide detailed information about the complaint..." required></textarea>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">
                        <i class="fas fa-times mr-1"></i>Cancel
                    </button>
                    <button type="button" id="registerComplaintBtn" class="btn btn-warning" onclick="registerComplaint()">
                        <i class="fas fa-exclamation-triangle mr-1"></i>Register Complaint
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Bootstrap core JavaScript-->
    <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>
            $(document).ready(function() {
            // Hide sidebar on load for a focused, full-width mobile-like view
            $('body').addClass('sidebar-toggled');
            $('.sidebar').addClass('toggled');
            if ($('.sidebar').hasClass('toggled')) {
                $('.sidebar .collapse').collapse('hide');
            }

            // Add animation on page load
            $('.customer-card').each(function(index) {
                $(this).css('opacity', '0').css('transform', 'translateY(30px)');
                $(this).delay(index * 50).animate({
                    opacity: 1
                }, 400, function() {
                    $(this).css('transform', 'translateY(0)');
                });
            });
            
            // Search functionality
            $('#customerSearch').on('keyup', function() {
                const searchTerm = $(this).val().toLowerCase();
                
                $('.customer-item').each(function() {
                    const customerName = $(this).data('name') || '';
                    const mobile = $(this).data('mobile') || '';
                    const altPhone = $(this).data('alt-phone') || '';
                    const outstanding = $(this).data('outstanding') || 0;
                    
                    const isMatch = customerName.toString().toLowerCase().includes(searchTerm) || 
                                   mobile.toString().toLowerCase().includes(searchTerm) || 
                                   altPhone.toString().toLowerCase().includes(searchTerm) ||
                                   outstanding.toString().includes(searchTerm);
                    
                    if (isMatch) {
                        $(this).show();
                    } else {
                        $(this).hide();
                    }
                });
                
                // Update results count
                const visibleCount = $('.customer-item:visible').length;
                if (searchTerm === '') {
                    // Show all customers message when search is empty
                    console.log('Showing all customers');
                } else {
                    console.log('Found ' + visibleCount + ' customer(s) matching "' + searchTerm + '"');
                }
            });
            
            // POS button click effect
            $('.pos-btn').on('click', function() {
                $(this).html('<i class="fas fa-spinner fa-spin mr-2"></i>Loading POS...');
            });



            // Payment method toggle for reference field
            $('#collectMethod').on('change', function(){
                const method = $(this).val();
                if (['Bank Transfer', 'UPI', 'Cheque', 'Card', 'Online'].includes(method)) {
                    $('#collectRefGroup').show();
                } else {
                    $('#collectRefGroup').hide();
                    $('#collectReference').val('');
                }
            });
            
            // Populate 12-hour time controls
        (function populateReminderTimeControls(){
                const $h = $('#reminderHour12');
                const $m = $('#reminderMinute');
                if ($h.children().length === 0) {
                    for (let i=1;i<=12;i++) {
                        const v = i.toString();
                        $h.append(`<option value="${v}">${v.padStart(2,'0')}</option>`);
                    }
                }
                if ($m.children().length === 0) {
            ['15','30','45'].forEach(v => $m.append(`<option value="${v}">${v}</option>`));
                }
            })();
        });
        
        // Filter functions
        function filterOutstandingCustomers() {
            $('.customer-item').each(function() {
                const outstanding = parseFloat($(this).data('outstanding')) || 0;
                if (outstanding > 0) {
                    $(this).show();
                } else {
                    $(this).hide();
                }
            });
        }
        
        function filterAdvanceCustomers() {
            $('.customer-item').each(function() {
                const outstanding = parseFloat($(this).data('outstanding')) || 0;
                if (outstanding < 0) {
                    $(this).show();
                } else {
                    $(this).hide();
                }
            });
        }
        
        function showAllCustomers() {
            $('.customer-item').show();
            $('#customerSearch').val('');
        }

        // Test function for debugging
        function testDropdown() {
            console.log('Test function called');
            alert('JavaScript is working!');
        }

        // Global variables to store current customer info
        var currentCustomerId = null;
        var currentCustomerName = null;

        // Open actions modal
        function openActionsModal(customerId, customerName) {
            console.log('Opening actions modal for customer:', customerId, customerName);
            
            // Store customer info globally
            currentCustomerId = customerId;
            currentCustomerName = customerName;
            
            // Update modal content
            $('#actionsCustomerName').text(customerName);
            
            // Show the modal
            $('#customerActionsModal').modal('show');
        }

        // Open complaint modal from actions modal
        function openComplaintModalFromActions() {
            $('#customerActionsModal').modal('hide');
            setTimeout(function() {
                openComplaintModal(currentCustomerId, currentCustomerName);
            }, 300);
        }

        // Open reminder modal from actions modal
        function openReminderModalFromActions() {
            $('#customerActionsModal').modal('hide');
            setTimeout(function() {
                openReminderModal(currentCustomerId, currentCustomerName);
            }, 300);
        }

        // View transaction history
        function viewTransactionHistory() {
            window.location.href = 'transaction-history.php?customer_id=' + currentCustomerId;
        }

        // Edit customer
        function editCustomer() {
            window.location.href = 'customer-management.php?edit=' + currentCustomerId;
        }

        // Open complaint modal
        function openComplaintModal(customerId, customerName) {
            $('#complaintCustomerId').val(customerId);
            $('#complaintCustomerName').val(customerName);
            
            // Load rice bags for selection
            loadRiceBags();
            
            // Reset form
            $('#complaintForm')[0].reset();
            $('#complaintCustomerId').val(customerId);
            $('#complaintCustomerName').val(customerName);
            
            // Show modal
            $('#complaintModal').modal('show');
            
            // Close any open dropdowns
            $('.dropdown-menu').removeClass('show');
        }

        // Load rice bags for complaint form
        function loadRiceBags() {
            $.ajax({
                url: 'api/get-rice-bag.php',
                method: 'GET',
                dataType: 'json',
                success: function(response) {
                    if (response.success) {
                        const select = $('#complaintRiceBag');
                        select.empty().append('<option value="">Select Rice Bag Product</option>');
                        
                        response.data.forEach(function(bag) {
                            select.append(`<option value="${bag.ID}">${bag.RiceBagName} - ${bag.Brand} (${bag.BagKg}kg)</option>`);
                        });
                    } else {
                        console.error('Failed to load rice bags:', response.message);
                    }
                },
                error: function(xhr, status, error) {
                    console.error('Error loading rice bags:', error);
                }
            });
        }

        // Register complaint
        function registerComplaint() {
            const formData = {
                customer_id: $('#complaintCustomerId').val(),
                rice_bag_id: $('#complaintRiceBag').val(),
                complaint_type: $('#complaintType').val(),
                complaint_title: $('#complaintTitle').val(),
                complaint_description: $('#complaintDescription').val(),
                priority: $('#complaintPriority').val()
            };

            // Validate required fields
            if (!formData.rice_bag_id) {
                alert('Please select a rice bag product');
                return;
            }
            
            if (!formData.complaint_title.trim()) {
                alert('Please enter a complaint title');
                return;
            }
            
            if (!formData.complaint_description.trim()) {
                alert('Please enter complaint details');
                return;
            }

            // Show loading state
            const submitBtn = $('#registerComplaintBtn');
            const originalText = submitBtn.html();
            submitBtn.prop('disabled', true).html('<i class="fas fa-spinner fa-spin mr-1"></i>Registering...');

            // Submit complaint
            $.ajax({
                url: 'api/complaints.php',
                method: 'POST',
                data: JSON.stringify(formData),
                contentType: 'application/json',
                dataType: 'json',
                success: function(response) {
                    if (response.success) {
                        alert(`Complaint registered successfully!\nComplaint Number: ${response.data.complaint_number}`);
                        $('#complaintModal').modal('hide');
                        $('#complaintForm')[0].reset();
                    } else {
                        alert('Error registering complaint: ' + response.message);
                    }
                },
                error: function(xhr, status, error) {
                    console.error('Error registering complaint:', error);
                    alert('Error registering complaint. Please try again.');
                },
                complete: function() {
                    submitBtn.prop('disabled', false).html(originalText);
                }
            });
        }

        // Open Collect Payment modal for a customer
        function openPaymentCollectModal(customerId, customerName) {
            $('#collectCustomerId').val(customerId);
            $('#collectCustomerName').text(customerName);
            $('#paymentCollectForm')[0]?.reset?.();
            // default values
            $('#collectTransactionType').val('Credit');
            $('#collectMethod').val('Cash').trigger('change');
            const today = new Date().toISOString().split('T')[0];
            $('#collectDate').val(today);
            $('#paymentCollectModal').modal('show');
        }

        // Save payment via API and update UI
        function savePaymentCollect() {
            const customerId = parseInt($('#collectCustomerId').val(), 10);
            const transactionType = $('#collectTransactionType').val();
            const amount = parseFloat($('#collectAmount').val());
            const method = $('#collectMethod').val();
            const reference = ($('#collectReference').val() || '').trim();
            const description = ($('#collectDescription').val() || '').trim();
            const paymentDate = $('#collectDate').val();

            if (!customerId) { alert('Invalid customer.'); return; }
            if (!amount || amount <= 0) { alert('Enter a valid amount.'); return; }
            if (!paymentDate) { alert('Select a payment date.'); return; }

            const payload = {
                customer_id: customerId,
                transaction_type: transactionType,
                amount: amount,
                payment_method: method,
                reference_number: reference,
                description: description,
                payment_date: paymentDate
            };

            const btn = $('#collectSaveBtn');
            const prev = btn.html();
            btn.prop('disabled', true).html('<i class="fas fa-spinner fa-spin mr-1"></i>Saving...');

            $.ajax({
                url: 'api/record-payment.php',
                method: 'POST',
                data: JSON.stringify(payload),
                contentType: 'application/json',
                dataType: 'json',
                success: function(resp) {
                    if (resp && resp.success) {
                        $('#paymentCollectModal').modal('hide');
                        alert('Payment recorded successfully');

                        // Update outstanding amount badge and data attribute on the card
                        const card = $('#customer-item-' + customerId);
                        let currentOutstanding = parseFloat(card.data('outstanding')) || 0;
                        let newOutstanding = currentOutstanding;
                        if (transactionType === 'Credit') {
                            newOutstanding = currentOutstanding - amount; // money received reduces outstanding
                        } else { // Debit
                            newOutstanding = currentOutstanding + amount; // money paid increases outstanding
                        }

                        // Persist new outstanding on DOM dataset
                        card.attr('data-outstanding', newOutstanding);

                        // Update displayed badge text and style (advance/zero/positive)
                        const badge = $('#outstanding-amt-' + customerId);
                        if (newOutstanding > 0) {
                            badge.removeClass('advance zero').addClass('').text('₹' + Math.round(newOutstanding));
                        } else if (newOutstanding < 0) {
                            badge.removeClass('zero').addClass('advance').text('₹' + Math.round(Math.abs(newOutstanding)) + ' Adv');
                        } else {
                            badge.removeClass('advance').addClass('zero').text('₹0');
                        }
                    } else {
                        alert('Error: ' + (resp && resp.message ? resp.message : 'Failed to record payment'));
                    }
                },
                error: function(xhr) {
                    let msg = 'Failed to record payment';
                    try { const j = JSON.parse(xhr.responseText); if (j.message) msg = j.message; } catch(e) {}
                    alert(msg);
                },
                complete: function(){ btn.prop('disabled', false).html(prev); }
            });
        }
        
        // Reminder functions
        function openReminderModal(customerId, customerName) {
            $('#reminderCustomerId').val(customerId);
            $('#customerNameDisplay').text(customerName);
            
            // Set default date to today and time to current time + 1 hour (12-hour format)
            const now = new Date();
            const today = now.toISOString().split('T')[0];
            let h24 = now.getHours() + 1; // next hour
            let min = now.getMinutes();
            if (h24 >= 24) h24 = 23; // clamp to same day
            const ampm = (h24 >= 12) ? 'PM' : 'AM';
            let h12 = h24 % 12; if (h12 === 0) h12 = 12;
            $('#reminderDate').val(today);
            $('#reminderHour12').val(String(h12));
            // Choose allowed minute value (15, 30, 45) based on current minutes
            let minuteChoice = '15';
            if (min <= 15) minuteChoice = '15';
            else if (min <= 30) minuteChoice = '30';
            else minuteChoice = '45';
            $('#reminderMinute').val(minuteChoice);
            $('#reminderAmPm').val(ampm);
            $('#reminderText').val('');
            
            $('#reminderModal').modal('show');
        }
        
        function saveReminder() {
            const customerId = $('#reminderCustomerId').val();
            const reminderDate = $('#reminderDate').val();
            const hour12 = parseInt($('#reminderHour12').val() || '12', 10);
            const minute = parseInt($('#reminderMinute').val() || '0', 10);
            const ampm = $('#reminderAmPm').val() || 'AM';
            const reminderText = $('#reminderText').val();
            
            if (!reminderDate) {
                alert('Please select both date and time for the reminder.');
                return;
            }
            
            // Convert 12-hour to 24-hour and combine into datetime format
            let hh = hour12 % 12; // 0-11
            if (ampm === 'PM') hh += 12; // 12-23
            const hhStr = String(hh).padStart(2, '0');
            const mmStr = String(minute).padStart(2, '0');
            const reminderDateTime = `${reminderDate} ${hhStr}:${mmStr}:00`;
            
            // Show loading state
            const saveBtn = $('.modal-footer .btn-primary');
            const originalText = saveBtn.html();
            saveBtn.html('<i class="fas fa-spinner fa-spin mr-1"></i>Saving...').prop('disabled', true);
            
            $.ajax({
                url: 'api/customer-reminders.php',
                method: 'POST',
                dataType: 'json',
                data: {
                    action: 'add',
                    customerId: customerId,
                    reminderDateTime: reminderDateTime,
                    reminderText: reminderText
                },
                success: function(result) {
                    if (result && result.success) {
                        $('#reminderModal').modal('hide');
                        alert('Reminder added successfully!');
                        // Reload the page to show updated reminder info
                        location.reload();
                    } else {
                        const msg = (result && result.message) ? result.message : 'Failed to add reminder';
                        alert('Error: ' + msg);
                    }
                },
                error: function(xhr) {
                    let msg = 'Failed to connect to server';
                    try {
                        const j = JSON.parse(xhr.responseText || '{}');
                        if (j && j.message) msg = j.message;
                    } catch (e) { /* ignore */ }
                    alert('Error: ' + msg);
                },
                complete: function() {
                    saveBtn.html(originalText).prop('disabled', false);
                }
            });
        }
    </script>
</body>
</html>
