<?php
require_once 'auth.php';
requireAdminLogin();

require_once '../config/database.php';
$pdo = getDBConnection();

$success_messages = [];
$error_messages = [];

try {
    // Helper function to update settings
    function updateSetting($pdo, $key, $value) {
        $stmt = $pdo->prepare("INSERT INTO settings (setting_key, setting_value) VALUES (?, ?) ON DUPLICATE KEY UPDATE setting_value = ?");
        return $stmt->execute([$key, $value, $value]);
    }
    
    // 1. Enable tatkal in settings
    updateSetting($pdo, 'tatkal_enabled', '1');
    $success_messages[] = "✅ Tatkal enabled in settings";
    
    // 2. Set proper tatkal price
    updateSetting($pdo, 'tatkal_price', '1500');
    $success_messages[] = "✅ Tatkal price set to ₹1500";
    
    // 3. Fix consultation type
    $checkStmt = $pdo->prepare("SELECT COUNT(*) FROM consultation_types WHERE type_code = 'tatkal_booking'");
    $checkStmt->execute();
    $count = $checkStmt->fetchColumn();
    
    if ($count == 0) {
        // Create new consultation type
        $createStmt = $pdo->prepare("
            INSERT INTO consultation_types (type_name, type_code, base_price, description, is_active) VALUES
            (?, ?, ?, ?, ?)
        ");
        $createStmt->execute(['Tatkal Booking', 'tatkal_booking', 1500.00, 'Emergency/urgent consultation booking', 1]);
        $success_messages[] = "✅ Created tatkal consultation type";
    } else {
        // Update existing consultation type
        $updateStmt = $pdo->prepare("UPDATE consultation_types SET base_price = ?, is_active = ? WHERE type_code = ?");
        $updateStmt->execute([1500.00, 1, 'tatkal_booking']);
        $success_messages[] = "✅ Updated tatkal consultation type (activated & price fixed)";
    }
    
    // 4. Enable default tatkal days
    $defaultDays = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday'];
    foreach ($defaultDays as $day) {
        updateSetting($pdo, 'tatkal_' . $day . '_enabled', '1');
    }
    $success_messages[] = "✅ Enabled tatkal for weekdays";
    
    // 5. Set default slots and advance days
    updateSetting($pdo, 'tatkal_slots', '10');
    updateSetting($pdo, 'tatkal_advance_days', '7');
    $success_messages[] = "✅ Set default slots (10) and advance days (7)";
    
    // 6. Verify all settings
    $verifyStmt = $pdo->prepare("SELECT setting_value FROM settings WHERE setting_key = ?");
    $verifyStmt->execute(['tatkal_enabled']);
    $tatkalEnabled = $verifyStmt->fetchColumn();
    
    $verifyStmt->execute(['tatkal_price']);
    $tatkalPrice = $verifyStmt->fetchColumn();
    
    $consultationStmt = $pdo->prepare("SELECT is_active, base_price FROM consultation_types WHERE type_code = 'tatkal_booking'");
    $consultationStmt->execute();
    $consultationType = $consultationStmt->fetch(PDO::FETCH_ASSOC);
    
    if ($tatkalEnabled == '1' && $tatkalPrice == '1500' && $consultationType && $consultationType['is_active'] == 1) {
        $success_messages[] = "🎉 All verifications passed! Tatkal is fully configured.";
    } else {
        $error_messages[] = "⚠️ Some settings may not have been applied correctly. Please check manually.";
    }
    
} catch (Exception $e) {
    $error_messages[] = "❌ Error: " . $e->getMessage();
    error_log("Tatkal Fix Error: " . $e->getMessage());
}

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Tatkal Fix Results</title>
    <style>
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            margin: 0;
            padding: 20px;
            min-height: 100vh;
        }
        
        .container {
            max-width: 800px;
            margin: 0 auto;
            background: white;
            border-radius: 15px;
            padding: 30px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.2);
        }
        
        .title {
            text-align: center;
            color: #333;
            margin-bottom: 30px;
            font-size: 2rem;
        }
        
        .message {
            padding: 15px;
            margin: 10px 0;
            border-radius: 8px;
            font-size: 16px;
        }
        
        .success {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        
        .error {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        
        .actions {
            text-align: center;
            margin-top: 30px;
        }
        
        .btn {
            display: inline-block;
            padding: 12px 24px;
            margin: 10px;
            text-decoration: none;
            border-radius: 6px;
            font-weight: 600;
            transition: all 0.3s ease;
        }
        
        .btn-primary {
            background: #007bff;
            color: white;
        }
        
        .btn-success {
            background: #28a745;
            color: white;
        }
        
        .btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 15px rgba(0,0,0,0.2);
        }
    </style>
</head>
<body>
    <div class="container">
        <h1 class="title">🔥 Tatkal Fix Results</h1>
        
        <?php foreach ($success_messages as $message): ?>
            <div class="message success"><?php echo $message; ?></div>
        <?php endforeach; ?>
        
        <?php foreach ($error_messages as $message): ?>
            <div class="message error"><?php echo $message; ?></div>
        <?php endforeach; ?>
        
        <?php if (empty($error_messages)): ?>
            <div class="message success">
                <strong>🎉 All fixes applied successfully!</strong><br>
                Tatkal booking should now work properly in the app.
            </div>
        <?php endif; ?>
        
        <div class="actions">
            <a href="debug_tatkal.php" class="btn btn-primary">🔍 Check Debug Page</a>
            <a href="tatkal_management_panel.php" class="btn btn-success">⚙️ Tatkal Management</a>
        </div>
    </div>
</body>
</html>
