<?php
// Test script specifically for date blocking functionality
session_start();
require_once 'config/database.php';

echo "<h1>🧪 Testing Date Blocking Functionality</h1>";
echo "<style>body{font-family:Arial,sans-serif;margin:20px;} .success{color:green;} .error{color:red;} .info{color:blue;}</style>";

try {
    $pdo = getDBConnection();
    echo "<p class='success'>✅ Database connection successful</p>";
    
    // Test blocked_dates table
    echo "<h2>1. Testing Blocked Dates Table</h2>";
    try {
        $stmt = $pdo->query("DESCRIBE blocked_dates");
        $columns = $stmt->fetchAll();
        echo "<p class='success'>✅ blocked_dates table exists with columns:</p>";
        echo "<ul>";
        foreach ($columns as $col) {
            echo "<li><strong>{$col['Field']}</strong> - {$col['Type']}</li>";
        }
        echo "</ul>";
    } catch (Exception $e) {
        echo "<p class='error'>❌ blocked_dates table not found: " . $e->getMessage() . "</p>";
        echo "<p class='info'>💡 Run setup_blocked_dates.php to create the table</p>";
    }
    
    // Test date blocking
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['test_block_date'])) {
        echo "<h2>2. Testing Date Blocking</h2>";
        
        $test_date = $_POST['test_block_date'];
        $test_reason = $_POST['test_reason'] ?? 'Test blocking';
        
        echo "<p><strong>Attempting to block date:</strong> $test_date</p>";
        echo "<p><strong>Reason:</strong> $test_reason</p>";
        
        try {
            // Validate date
            if (empty($test_date)) {
                throw new Exception('Date is required for blocking');
            }
            
            // Validate date format
            $date_obj = DateTime::createFromFormat('Y-m-d', $test_date);
            if (!$date_obj || $date_obj->format('Y-m-d') !== $test_date) {
                throw new Exception('Invalid date format. Please use YYYY-MM-DD format');
            }
            
            // Check if date is in the past
            $today = new DateTime();
            $today->setTime(0, 0, 0);
            if ($date_obj < $today) {
                throw new Exception('Cannot block past dates. Please select a future date.');
            }
            
            // Check if date already exists
            $stmt = $pdo->prepare("SELECT id FROM blocked_dates WHERE block_date = ?");
            $stmt->execute([$test_date]);
            
            if ($stmt->fetch()) {
                echo "<p class='info'>ℹ️ Date $test_date is already blocked!</p>";
            } else {
                // Insert new blocked date
                $stmt = $pdo->prepare("INSERT INTO blocked_dates (block_date, reason, created_by) VALUES (?, ?, ?)");
                $stmt->execute([$test_date, $test_reason, 'test_user']);
                echo "<p class='success'>✅ Date $test_date blocked successfully!</p>";
            }
        } catch (Exception $e) {
            echo "<p class='error'>❌ Error blocking date: " . $e->getMessage() . "</p>";
        }
    }
    
    // Show test form
    echo "<h2>3. Test Date Blocking Form</h2>";
    echo "<form method='POST'>";
    echo "<p><label>Test Date: <input type='date' name='test_block_date' value='" . date('Y-m-d', strtotime('+1 day')) . "' min='" . date('Y-m-d') . "' required></label></p>";
    echo "<p><label>Test Reason: <input type='text' name='test_reason' value='Test blocking " . date('Y-m-d') . "' maxlength='255'></label></p>";
    echo "<p><button type='submit' name='test_block_date'>Test Block Date</button></p>";
    echo "</form>";
    
    // Show current blocked dates
    echo "<h2>4. Current Blocked Dates</h2>";
    try {
        $stmt = $pdo->query("SELECT * FROM blocked_dates ORDER BY block_date DESC LIMIT 10");
        $blocked_dates = $stmt->fetchAll();
        if (empty($blocked_dates)) {
            echo "<p class='info'>ℹ️ No dates are currently blocked</p>";
        } else {
            echo "<p class='success'>✅ Found " . count($blocked_dates) . " blocked dates:</p>";
            echo "<ul>";
            foreach ($blocked_dates as $date) {
                echo "<li><strong>" . date('d M Y', strtotime($date['block_date'])) . "</strong> - " . htmlspecialchars($date['reason']) . " (by " . htmlspecialchars($date['created_by']) . ")</li>";
            }
            echo "</ul>";
        }
    } catch (Exception $e) {
        echo "<p class='error'>❌ Error reading blocked dates: " . $e->getMessage() . "</p>";
    }
    
    // Test unblocking
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['test_unblock_date'])) {
        echo "<h2>5. Testing Date Unblocking</h2>";
        $date_id = $_POST['date_id'];
        
        try {
            $stmt = $pdo->prepare("DELETE FROM blocked_dates WHERE id = ?");
            $stmt->execute([$date_id]);
            echo "<p class='success'>✅ Date unblocked successfully!</p>";
        } catch (Exception $e) {
            echo "<p class='error'>❌ Error unblocking date: " . $e->getMessage() . "</p>";
        }
    }
    
    // Show unblock form for test dates
    try {
        $stmt = $pdo->query("SELECT * FROM blocked_dates WHERE reason LIKE 'Test blocking%' ORDER BY block_date DESC");
        $test_dates = $stmt->fetchAll();
        if (!empty($test_dates)) {
            echo "<h2>6. Unblock Test Dates</h2>";
            echo "<p class='info'>ℹ️ Test dates that can be unblocked:</p>";
            foreach ($test_dates as $date) {
                echo "<form method='POST' style='display:inline; margin-right:10px;'>";
                echo "<input type='hidden' name='date_id' value='{$date['id']}'>";
                echo "<button type='submit' name='test_unblock_date' class='btn btn-sm btn-outline-danger'>";
                echo "Unblock " . date('d M Y', strtotime($date['block_date']));
                echo "</button>";
                echo "</form>";
            }
        }
    } catch (Exception $e) {
        echo "<p class='error'>❌ Error reading test dates: " . $e->getMessage() . "</p>";
    }
    
    echo "<hr>";
    echo "<p><a href='admin/settings.php'>🔧 Go to Main Settings</a></p>";
    echo "<p><a href='setup_blocked_dates.php'>⚙️ Setup Blocked Dates Table</a></p>";
    
} catch (Exception $e) {
    echo "<p class='error'>❌ Database connection failed: " . $e->getMessage() . "</p>";
}
?> 