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

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    exit(0);
}

try {
    $pdo = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $user_id = getUserIdFromToken($_COOKIE['auth_token'] ?? $_SERVER['HTTP_AUTHORIZATION'] ?? null);

    if ($_SERVER['REQUEST_METHOD'] === 'GET') {
        if (!$user_id) {
            throw new Exception('Authentication required');
        }

        $type = $_GET['type'] ?? 'all';
        
        if ($type === 'preferences') {
            // Get notification preferences
            $stmt = $pdo->prepare("
                SELECT * FROM notification_preferences 
                WHERE user_id = ?
            ");
            $stmt->execute([$user_id]);
            $preferences = $stmt->fetch(PDO::FETCH_ASSOC);
            
            if (!$preferences) {
                // Create default preferences
                $stmt = $pdo->prepare("
                    INSERT INTO notification_preferences (user_id) VALUES (?)
                ");
                $stmt->execute([$user_id]);
                
                $stmt = $pdo->prepare("
                    SELECT * FROM notification_preferences WHERE user_id = ?
                ");
                $stmt->execute([$user_id]);
                $preferences = $stmt->fetch(PDO::FETCH_ASSOC);
            }
            
            echo json_encode([
                'success' => true,
                'preferences' => $preferences
            ]);
            
        } else {
            // Get user notifications
            $limit = $_GET['limit'] ?? 20;
            $offset = $_GET['offset'] ?? 0;
            
            $stmt = $pdo->prepare("
                SELECT * FROM user_notifications 
                WHERE user_id = ? 
                ORDER BY created_at DESC 
                LIMIT ? OFFSET ?
            ");
            $stmt->execute([$user_id, $limit, $offset]);
            $notifications = $stmt->fetchAll(PDO::FETCH_ASSOC);
            
            // Get unread count
            $stmt = $pdo->prepare("
                SELECT COUNT(*) as unread_count 
                FROM user_notifications 
                WHERE user_id = ? AND is_read = FALSE
            ");
            $stmt->execute([$user_id]);
            $unread = $stmt->fetch(PDO::FETCH_ASSOC);
            
            echo json_encode([
                'success' => true,
                'notifications' => $notifications,
                'unread_count' => $unread['unread_count']
            ]);
        }
        
    } elseif ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $input = json_decode(file_get_contents('php://input'), true);
        $action = $input['action'] ?? 'send';
        
        if ($action === 'send') {
            // Send notification (admin only)
            $admin_user = getCurrentUser();
            if (!$admin_user || $admin_user['role'] !== 'admin') {
                throw new Exception('Admin access required');
            }
            
            $required = ['user_id', 'type', 'title', 'message'];
            foreach ($required as $field) {
                if (empty($input[$field])) {
                    throw new Exception("$field is required");
                }
            }
            
            $stmt = $pdo->prepare("
                INSERT INTO user_notifications (user_id, type, title, message, data)
                VALUES (?, ?, ?, ?, ?)
            ");
            $stmt->execute([
                $input['user_id'],
                $input['type'],
                $input['title'],
                $input['message'],
                json_encode($input['data'] ?? [])
            ]);
            
            echo json_encode([
                'success' => true,
                'message' => 'Notification sent successfully'
            ]);
            
        } elseif ($action === 'mark_read') {
            if (!$user_id) {
                throw new Exception('Authentication required');
            }
            
            $notification_id = $input['notification_id'] ?? null;
            
            if ($notification_id) {
                // Mark specific notification as read
                $stmt = $pdo->prepare("
                    UPDATE user_notifications 
                    SET is_read = TRUE, read_at = NOW() 
                    WHERE id = ? AND user_id = ?
                ");
                $stmt->execute([$notification_id, $user_id]);
            } else {
                // Mark all as read
                $stmt = $pdo->prepare("
                    UPDATE user_notifications 
                    SET is_read = TRUE, read_at = NOW() 
                    WHERE user_id = ? AND is_read = FALSE
                ");
                $stmt->execute([$user_id]);
            }
            
            echo json_encode([
                'success' => true,
                'message' => 'Notifications marked as read'
            ]);
        }
        
    } elseif ($_SERVER['REQUEST_METHOD'] === 'PUT') {
        // Update notification preferences
        if (!$user_id) {
            throw new Exception('Authentication required');
        }
        
        $input = json_decode(file_get_contents('php://input'), true);
        
        $stmt = $pdo->prepare("
            UPDATE notification_preferences SET
                email_appointments = ?,
                email_reminders = ?,
                email_marketing = ?,
                sms_appointments = ?,
                sms_reminders = ?,
                push_appointments = ?,
                push_reminders = ?,
                push_marketing = ?
            WHERE user_id = ?
        ");
        
        $stmt->execute([
            $input['email_appointments'] ?? true,
            $input['email_reminders'] ?? true,
            $input['email_marketing'] ?? true,
            $input['sms_appointments'] ?? true,
            $input['sms_reminders'] ?? true,
            $input['push_appointments'] ?? true,
            $input['push_reminders'] ?? true,
            $input['push_marketing'] ?? false,
            $user_id
        ]);
        
        echo json_encode([
            'success' => true,
            'message' => 'Preferences updated successfully'
        ]);
    }

} catch (Exception $e) {
    http_response_code(400);
    echo json_encode([
        'success' => false,
        'error' => $e->getMessage()
    ]);
}
?>