<?php
require_once '../config.php';
require_once '../app/classes/AdminAuth.php';
require_once '../app/classes/LowBalanceAlert.php';

$adminAuth = new AdminAuth($conn);

// Check if admin is authenticated
if (!$adminAuth->isAuthenticated()) {
    header('Location: admin_login.php');
    exit();
}

$lowBalanceAlert = new LowBalanceAlert($conn);
$message = '';
$messageType = '';

// Handle manual check execution
$checkResult = null;
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['run_manual_check'])) {
    try {
        // Check if force send is requested (bypass interval)
        $forceSend = isset($_POST['force_send']) && $_POST['force_send'] == '1';
        $checkResult = $lowBalanceAlert->processAlerts($forceSend);
        if ($checkResult['total'] > 0) {
            $forceNote = $forceSend ? " (forced - interval ignored)" : "";
            $message = "Low balance check completed! Found {$checkResult['total']} user(s) needing alerts{$forceNote}. Sent: {$checkResult['sent']}, Failed: {$checkResult['failed']}";
            $messageType = $checkResult['failed'] > 0 ? 'warning' : 'success';
        } else {
            $message = "Low balance check completed! No users need alerts at this time.";
            $messageType = 'success';
        }
    } catch (Exception $e) {
        $message = 'Error running manual check: ' . $e->getMessage();
        $messageType = 'error';
    }
}

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_low_balance_config'])) {
    $enabled = isset($_POST['low_balance_alert_enabled']) ? 1 : 0;
    $thresholdAmount = floatval($_POST['low_balance_threshold'] ?? 50.00);
    $intervalDays = intval($_POST['low_balance_alert_interval'] ?? 2);
    
    if ($thresholdAmount < 0) {
        $message = 'Threshold amount cannot be negative.';
        $messageType = 'error';
    } elseif ($intervalDays < 1) {
        $message = 'Alert interval must be at least 1 day.';
        $messageType = 'error';
    } else {
        $result = $lowBalanceAlert->updateConfig($enabled, $thresholdAmount, $intervalDays);
        if ($result) {
            $message = 'Low balance alert configuration updated successfully!';
            $messageType = 'success';
        } else {
            $message = 'Failed to update configuration.';
            $messageType = 'error';
        }
    }
}

// Get current configuration
$config = $lowBalanceAlert->getConfig();

// Get statistics (refresh after manual check)
$usersNeedingAlerts = $lowBalanceAlert->getUsersNeedingAlerts();
$totalLowBalanceUsers = count($usersNeedingAlerts);

// For debugging: Get all users with low balance (regardless of alert status)
$allLowBalanceUsers = $lowBalanceAlert->getAllUsersWithLowBalance();
$totalAllLowBalance = count($allLowBalanceUsers);

// Set page variables for header
$page_title = 'Low Balance Alert Configuration';
$page_description = 'Configure low balance alerts for users';
?>

<div class="space-y-6">
    <!-- Page Header -->
    <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
        <div class="flex items-center justify-between">
            <div>
                <h1 class="text-2xl font-bold text-gray-900">Low Balance Alert Configuration</h1>
                <p class="text-sm text-gray-600 mt-1">Configure automatic SMS alerts when user balances fall below a threshold</p>
            </div>
            <div class="flex items-center space-x-2">
                <div class="bg-blue-100 text-blue-800 px-4 py-2 rounded-lg">
                    <span class="text-sm font-medium">Users Needing Alerts: </span>
                    <span class="text-lg font-bold"><?= $totalLowBalanceUsers ?></span>
                </div>
                <?php if ($totalAllLowBalance > $totalLowBalanceUsers): ?>
                <div class="bg-yellow-100 text-yellow-800 px-4 py-2 rounded-lg">
                    <span class="text-sm font-medium">Total Low Balance: </span>
                    <span class="text-lg font-bold"><?= $totalAllLowBalance ?></span>
                    <span class="text-xs ml-1">(<?= $totalAllLowBalance - $totalLowBalanceUsers ?> waiting for interval)</span>
                </div>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <!-- Success/Error Messages -->
    <?php if ($message): ?>
    <div class="bg-<?= $messageType === 'success' ? 'green' : ($messageType === 'warning' ? 'yellow' : 'red') ?>-50 border border-<?= $messageType === 'success' ? 'green' : ($messageType === 'warning' ? 'yellow' : 'red') ?>-200 text-<?= $messageType === 'success' ? 'green' : ($messageType === 'warning' ? 'yellow' : 'red') ?>-800 px-4 py-3 rounded-lg">
        <div class="flex items-center">
            <i class="fas fa-<?= $messageType === 'success' ? 'check-circle' : ($messageType === 'warning' ? 'exclamation-triangle' : 'exclamation-circle') ?> mr-2"></i>
            <span><?= htmlspecialchars($message) ?></span>
        </div>
    </div>
    <?php endif; ?>

    <!-- Manual Check Section -->
    <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
        <div class="flex items-center justify-between mb-4">
            <div>
                <h2 class="text-xl font-semibold text-gray-900">Manual Balance Check</h2>
                <p class="text-sm text-gray-600 mt-1">Run a manual check to send alerts to users with low balance</p>
            </div>
            <form method="POST" class="inline">
                <input type="hidden" name="run_manual_check" value="1">
                <div class="flex items-center space-x-3">
                    <button type="submit" 
                            class="bg-green-600 text-white px-6 py-2 rounded-lg hover:bg-green-700 transition-colors flex items-center">
                        <i class="fas fa-play mr-2"></i>
                        Run Check Now
                    </button>
                    <label class="flex items-center cursor-pointer">
                        <input type="checkbox" 
                               name="force_send" 
                               value="1"
                               class="w-4 h-4 text-green-600 border-gray-300 rounded focus:ring-green-500">
                        <span class="ml-2 text-sm text-gray-700">
                            Force Send (ignore interval)
                        </span>
                    </label>
                </div>
                <p class="text-xs text-gray-500 mt-2">
                    <i class="fas fa-info-circle mr-1"></i>
                    Force Send will send alerts to all users with low balance, even if they received one recently.
                </p>
            </form>
        </div>
        
        <?php if ($checkResult !== null): ?>
        <div class="mt-4 bg-gray-50 rounded-lg p-4">
            <h3 class="text-sm font-semibold text-gray-700 mb-3">Check Results</h3>
            <div class="grid grid-cols-3 gap-4">
                <div class="text-center">
                    <div class="text-2xl font-bold text-blue-600"><?= $checkResult['total'] ?></div>
                    <div class="text-xs text-gray-600 mt-1">Total Users Found</div>
                </div>
                <div class="text-center">
                    <div class="text-2xl font-bold text-green-600"><?= $checkResult['sent'] ?></div>
                    <div class="text-xs text-gray-600 mt-1">Alerts Sent</div>
                </div>
                <div class="text-center">
                    <div class="text-2xl font-bold text-<?= $checkResult['failed'] > 0 ? 'red' : 'gray' ?>-600"><?= $checkResult['failed'] ?></div>
                    <div class="text-xs text-gray-600 mt-1">Failed</div>
                </div>
            </div>
        </div>
        <?php endif; ?>
    </div>

    <!-- Configuration Form -->
    <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
        <h2 class="text-xl font-semibold text-gray-900 mb-6">Alert Settings</h2>
        
        <form method="POST" class="space-y-6">
            <input type="hidden" name="update_low_balance_config" value="1">
            
            <!-- Enable/Disable -->
            <div class="bg-gray-50 rounded-lg p-4">
                <label class="flex items-center cursor-pointer">
                    <input type="checkbox" 
                           name="low_balance_alert_enabled" 
                           value="1" 
                           <?= $config['enabled'] ? 'checked' : '' ?>
                           class="w-5 h-5 text-blue-600 border-gray-300 rounded focus:ring-blue-500">
                    <span class="ml-3 text-sm font-medium text-gray-700">
                        Enable Low Balance Alerts
                    </span>
                </label>
                <p class="text-xs text-gray-500 mt-2 ml-8">
                    When enabled, users with balance below the threshold will receive automatic alerts at the configured interval.
                </p>
            </div>
            
            <!-- Threshold Amount -->
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">
                    Low Balance Threshold (GHS) *
                </label>
                <div class="relative">
                    <span class="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-500">₵</span>
                    <input type="number" 
                           name="low_balance_threshold" 
                           value="<?= htmlspecialchars($config['threshold_amount']) ?>" 
                           step="0.01" 
                           min="0" 
                           required
                           class="w-full pl-8 pr-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                </div>
                <p class="text-xs text-gray-500 mt-1">
                    Users with balance below this amount will receive alerts. Default: ₵50.00
                </p>
            </div>
            
            <!-- Alert Interval -->
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">
                    Alert Interval (Days) *
                </label>
                <input type="number" 
                       name="low_balance_alert_interval" 
                       value="<?= htmlspecialchars($config['alert_interval_days']) ?>" 
                       min="1" 
                       max="30"
                       required
                       class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                <p class="text-xs text-gray-500 mt-1">
                    How often to send alerts to users with low balance. For example, 2 means alerts will be sent every 2 days. Range: 1-30 days
                </p>
            </div>
            
            <!-- Submit Button -->
            <div class="flex justify-end space-x-3 pt-4 border-t border-gray-200">
                <button type="submit" 
                        class="bg-blue-600 text-white px-6 py-2 rounded-lg hover:bg-blue-700 transition-colors flex items-center">
                    <i class="fas fa-save mr-2"></i>
                    Save Configuration
                </button>
            </div>
        </form>
    </div>

    <!-- Users Needing Alerts -->
    <?php if ($config['enabled'] && $totalLowBalanceUsers > 0): ?>
    <div class="bg-white rounded-lg shadow-sm border border-gray-200 p-6">
        <h2 class="text-xl font-semibold text-gray-900 mb-4">Users Needing Alerts</h2>
        <div class="overflow-x-auto">
            <table class="min-w-full divide-y divide-gray-200">
                <thead class="bg-gray-50">
                    <tr>
                        <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Username</th>
                        <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Phone</th>
                        <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Balance</th>
                        <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Role</th>
                        <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Last Alert</th>
                    </tr>
                </thead>
                <tbody class="bg-white divide-y divide-gray-200">
                    <?php foreach ($usersNeedingAlerts as $user): ?>
                    <tr>
                        <td class="px-4 py-3 whitespace-nowrap text-sm font-medium text-gray-900">
                            <?= htmlspecialchars($user['username']) ?>
                        </td>
                        <td class="px-4 py-3 whitespace-nowrap text-sm text-gray-600">
                            <?= !empty($user['phone']) ? htmlspecialchars($user['phone']) : '<span class="text-red-500">No Phone</span>' ?>
                        </td>
                        <td class="px-4 py-3 whitespace-nowrap text-sm text-red-600 font-semibold">
                            ₵<?= number_format($user['balance'], 2) ?>
                        </td>
                        <td class="px-4 py-3 whitespace-nowrap text-sm text-gray-600">
                            <?= htmlspecialchars(ucfirst($user['role'])) ?>
                        </td>
                        <td class="px-4 py-3 whitespace-nowrap text-sm text-gray-600">
                            <?= $user['last_alert_date'] === '1970-01-01 00:00:00' ? 'Never' : date('Y-m-d H:i', strtotime($user['last_alert_date'])) ?>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
    <?php endif; ?>

    <!-- Information Box -->
    <div class="bg-blue-50 border border-blue-200 rounded-lg p-6">
        <h3 class="text-lg font-semibold text-blue-900 mb-3">
            <i class="fas fa-info-circle mr-2"></i>How It Works
        </h3>
        <ul class="space-y-2 text-sm text-blue-800">
            <li class="flex items-start">
                <i class="fas fa-check-circle mr-2 mt-0.5"></i>
                <span>The system automatically checks user balances and sends alerts based on your configuration.</span>
            </li>
            <li class="flex items-start">
                <i class="fas fa-check-circle mr-2 mt-0.5"></i>
                <span>Alerts are sent via SMS only using the configured SMS provider in notification settings.</span>
            </li>
            <li class="flex items-start">
                <i class="fas fa-check-circle mr-2 mt-0.5"></i>
                <span>Users will only receive alerts at the configured interval to avoid spam.</span>
            </li>
            <li class="flex items-start">
                <i class="fas fa-check-circle mr-2 mt-0.5"></i>
                <span>Set up a cron job to run the alert script daily: <code class="bg-blue-100 px-2 py-1 rounded">php cron/low_balance_alerts.php</code></span>
            </li>
        </ul>
    </div>
</div>

