<?php
require_once __DIR__ . '/api/lib.php';
hw_require_auth(['client']);
$authUser = hw_get_auth_user();

$db = hw_db();

// Check appointments
$stmt = $db->prepare("SELECT * FROM appointments WHERE user_id = ? ORDER BY starts_at DESC");
$stmt->execute([$authUser['id']]);
$appointments = $stmt->fetchAll(PDO::FETCH_ASSOC);

echo "<h1>Appointment Debug</h1>";
echo "<p>User ID: " . $authUser['id'] . "</p>";
echo "<p>User Name: " . htmlspecialchars($authUser['first_name'] . ' ' . $authUser['last_name']) . "</p>";
echo "<h2>Total Appointments: " . count($appointments) . "</h2>";

if (count($appointments) > 0) {
    echo "<table border='1' cellpadding='10'>";
    echo "<tr><th>ID</th><th>Coach ID</th><th>Starts At</th><th>Ends At</th><th>Status</th><th>Notes</th></tr>";
    foreach ($appointments as $apt) {
        echo "<tr>";
        echo "<td>" . $apt['id'] . "</td>";
        echo "<td>" . $apt['coach_id'] . "</td>";
        echo "<td>" . $apt['starts_at'] . "</td>";
        echo "<td>" . ($apt['ends_at'] ?? 'N/A') . "</td>";
        echo "<td>" . $apt['status'] . "</td>";
        echo "<td>" . htmlspecialchars($apt['notes'] ?? 'No notes') . "</td>";
        echo "</tr>";
    }
    echo "</table>";
    
    echo "<h2>Update Appointment Time</h2>";
    echo "<form method='post'>";
    echo "<input type='hidden' name='action' value='update'>";
    echo "<button type='submit' style='background: #f59e0b; color: white; padding: 12px 24px; border: none; border-radius: 8px; font-size: 16px; cursor: pointer; margin-right: 10px;'>Update to 30 Minutes from Now</button>";
    echo "</form>";
    
    echo "<h2>Delete Appointments</h2>";
    echo "<form method='post'>";
    echo "<input type='hidden' name='action' value='delete'>";
    echo "<button type='submit' style='background: #ef4444; color: white; padding: 12px 24px; border: none; border-radius: 8px; font-size: 16px; cursor: pointer;'>Delete All Appointments</button>";
    echo "</form>";
} else {
    echo "<h2>No Appointments Found</h2>";
    echo "<h3>Create Test Appointment</h3>";
    
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
        $action = $_POST['action'];
        
        if ($action === 'update') {
            // Update existing appointment to 30 minutes from now
            $startsAt = date('Y-m-d H:i:s', strtotime('+30 minutes'));
            $endsAt = date('Y-m-d H:i:s', strtotime('+90 minutes'));
            
            $updateStmt = $db->prepare("
                UPDATE appointments 
                SET starts_at = ?, ends_at = ?, status = 'scheduled'
                WHERE user_id = ?
            ");
            $updateStmt->execute([$startsAt, $endsAt, $authUser['id']]);
            
            echo "<p style='color: green;'><strong>✓ Appointments updated to 30 minutes from now!</strong></p>";
            echo "<p><a href='/atasteofafricanmarketplace/dashboard/user/appointments.php' style='background: #10b981; color: white; padding: 10px 20px; text-decoration: none; border-radius: 8px; display: inline-block;'>View Enhanced Appointments →</a></p>";
            echo "<script>setTimeout(() => window.location.reload(), 2000);</script>";
        } elseif ($action === 'delete') {
            // Delete all appointments
            $deleteStmt = $db->prepare("DELETE FROM appointments WHERE user_id = ?");
            $deleteStmt->execute([$authUser['id']]);
            
            echo "<p style='color: green;'><strong>✓ All appointments deleted!</strong></p>";
            echo "<script>setTimeout(() => window.location.reload(), 2000);</script>";
        }
    }
    
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && !isset($_POST['action'])) {
        // Get a coach
        $coachStmt = $db->prepare("SELECT id FROM coaches LIMIT 1");
        $coachStmt->execute();
        $coach = $coachStmt->fetch(PDO::FETCH_ASSOC);
        
        if ($coach) {
            // Create appointment 30 minutes from now
            $startsAt = date('Y-m-d H:i:s', strtotime('+30 minutes'));
            $endsAt = date('Y-m-d H:i:s', strtotime('+90 minutes'));
            
            $insertStmt = $db->prepare("
                INSERT INTO appointments (coach_id, user_id, starts_at, ends_at, status, notes, created_at)
                VALUES (?, ?, ?, ?, 'scheduled', 'This is a test appointment. Please prepare your questions about herbal wellness.', NOW())
            ");
            $insertStmt->execute([$coach['id'], $authUser['id'], $startsAt, $endsAt]);
            
            echo "<p style='color: green;'><strong>✓ Test appointment created successfully!</strong></p>";
            echo "<p>Refresh this page or go to <a href='/atasteofafricanmarketplace/dashboard/user/appointments.php'>appointments page</a></p>";
        } else {
            echo "<p style='color: red;'>No coaches found in database. Please create a coach first.</p>";
        }
    } else {
        echo "<form method='post'>";
        echo "<button type='submit' style='background: #10b981; color: white; padding: 12px 24px; border: none; border-radius: 8px; font-size: 16px; cursor: pointer;'>Create Test Appointment (30 min from now)</button>";
        echo "</form>";
    }
}
?>
