<?php
require_once __DIR__ . '/../lib.php';

hw_require_auth(['client']);

if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
    hw_json(['success' => false, 'error' => 'Method not allowed'], 405);
}

$authUser = hw_get_auth_user();

try {
    $db = hw_db();
    
    // Create notifications table if it doesn't exist
    $db->exec("
        CREATE TABLE IF NOT EXISTS notifications (
            id INT AUTO_INCREMENT PRIMARY KEY,
            user_id INT NOT NULL,
            type VARCHAR(50) NOT NULL,
            title VARCHAR(255) NOT NULL,
            message LONGTEXT,
            icon VARCHAR(100),
            color VARCHAR(50),
            is_read BOOLEAN DEFAULT FALSE,
            related_id INT,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
            KEY (user_id, created_at),
            KEY (user_id, is_read)
        )
    ");
    
    $limit = (int)($_GET['limit'] ?? 10);
    $offset = (int)($_GET['offset'] ?? 0);
    
    // Get upcoming appointments (unread by default)
    $appointmentsStmt = $db->prepare("
        SELECT 
            a.id,
            a.starts_at,
            CONCAT(u.first_name, ' ', u.last_name) as coach_name,
            c.display_name
        FROM appointments a
        LEFT JOIN coaches c ON a.coach_id = c.id
        LEFT JOIN users u ON c.user_id = u.id
        WHERE a.user_id = ? 
        AND a.status = 'scheduled' 
        AND a.starts_at > NOW()
        AND DATE(a.starts_at) <= DATE_ADD(NOW(), INTERVAL 3 DAY)
        ORDER BY a.starts_at ASC
        LIMIT 5
    ");
    $appointmentsStmt->execute([$authUser['id']]);
    $upcomingAppointments = $appointmentsStmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Build notifications array
    $notifications = [];
    
    // Session reminders for upcoming appointments
    foreach ($upcomingAppointments as $appt) {
        $startTime = new DateTime($appt['starts_at']);
        $now = new DateTime();
        $daysUntil = (int)$startTime->diff($now)->format('%d');
        
        if ($daysUntil === 0) {
            $timeStr = $startTime->format('g:i A');
            $title = "Session Today!";
            $message = "Your session with " . ($appt['display_name'] ?: $appt['coach_name']) . " is today at " . $timeStr;
        } elseif ($daysUntil === 1) {
            $timeStr = $startTime->format('g:i A');
            $title = "Session Tomorrow";
            $message = "Your session with " . ($appt['display_name'] ?: $appt['coach_name']) . " is tomorrow at " . $timeStr;
        } else {
            $dateStr = $startTime->format('l, F j');
            $timeStr = $startTime->format('g:i A');
            $title = "Upcoming Session";
            $message = "Session with " . ($appt['display_name'] ?: $appt['coach_name']) . " on " . $dateStr . " at " . $timeStr;
        }
        
        $notifications[] = [
            'id' => 'appt_' . $appt['id'],
            'type' => 'appointment',
            'title' => $title,
            'message' => $message,
            'icon' => 'fas fa-calendar',
            'color' => '#3b82f6',
            'is_read' => false,
            'related_id' => $appt['id'],
            'created_at' => $appt['starts_at']
        ];
    }
    
    // Get intake data for personalized recommendations
    $intakeStmt = $db->prepare("SELECT data FROM intake_forms WHERE user_id = ? ORDER BY created_at DESC LIMIT 1");
    $intakeStmt->execute([$authUser['id']]);
    $intakeData = $intakeStmt->fetch();
    $intake = $intakeData ? json_decode($intakeData['data'], true) : null;
    
    // Health recommendations based on intake
    if ($intake) {
        if (($intake['stressLevel'] ?? 0) > 7) {
            $notifications[] = [
                'id' => 'rec_stress',
                'type' => 'recommendation',
                'title' => 'Stress Management',
                'message' => 'Your stress level is high. Try meditation or lavender aromatherapy.',
                'icon' => 'fas fa-spa',
                'color' => '#a855f7',
                'is_read' => false,
                'created_at' => date('Y-m-d H:i:s')
            ];
        }
        
        if (($intake['sleepHours'] ?? 0) < 7) {
            $notifications[] = [
                'id' => 'rec_sleep',
                'type' => 'recommendation',
                'title' => 'Better Sleep',
                'message' => 'Consider chamomile tea and a consistent bedtime routine for better sleep.',
                'icon' => 'fas fa-moon',
                'color' => '#06b6d4',
                'is_read' => false,
                'created_at' => date('Y-m-d H:i:s')
            ];
        }
        
        if (empty($intake['exercise'])) {
            $notifications[] = [
                'id' => 'rec_exercise',
                'type' => 'recommendation',
                'title' => 'Stay Active',
                'message' => 'Start with 15-minute daily walks to boost your energy.',
                'icon' => 'fas fa-dumbbell',
                'color' => '#10b981',
                'is_read' => false,
                'created_at' => date('Y-m-d H:i:s')
            ];
        }
    }
    
    // Get coach notes/recommendations from database (if exists)
    $coachNotesStmt = $db->prepare("
        SELECT cn.id, cn.note, cn.created_at 
        FROM coach_notes cn
        JOIN appointments a ON cn.appointment_id = a.id
        WHERE a.user_id = ? AND cn.note_type = 'recommendation'
        ORDER BY cn.created_at DESC
        LIMIT 3
    ");
    $coachNotesStmt->execute([$authUser['id']]);
    $coachNotes = $coachNotesStmt->fetchAll(PDO::FETCH_ASSOC);
    
    foreach ($coachNotes as $note) {
        $notifications[] = [
            'id' => 'coach_' . $note['id'],
            'type' => 'coach_recommendation',
            'title' => 'Coach Recommendation',
            'message' => substr($note['note'], 0, 150) . (strlen($note['note']) > 150 ? '...' : ''),
            'icon' => 'fas fa-leaf',
            'color' => '#16a34a',
            'is_read' => false,
            'created_at' => $note['created_at']
        ];
    }
    
    // Sort by creation date (newest first)
    usort($notifications, function($a, $b) {
        return strtotime($b['created_at']) - strtotime($a['created_at']);
    });
    
    // Apply limit and offset
    $notifications = array_slice($notifications, $offset, $limit);
    
    // Count unread
    $unreadCount = count(array_filter($notifications, function($n) {
        return !$n['is_read'];
    }));
    
    hw_json([
        'success' => true,
        'notifications' => $notifications,
        'unread_count' => $unreadCount
    ]);
    
} catch (PDOException $e) {
    error_log('Notifications fetch error: ' . $e->getMessage());
    hw_json(['success' => false, 'error' => 'Database error'], 500);
} catch (Exception $e) {
    error_log('Notifications error: ' . $e->getMessage());
    hw_json(['success' => false, 'error' => 'Server error'], 500);
}
