<?php
// Required files
require_once '../config/cors.php';
require_once '../config/database.php';
// Note: Auth files are not used in this version for simplicity.
// require_once '../middleware/auth.php';
// require_once '../utils/jwt.php';

// --- DATABASE CONNECTION ---
$database = new Database();
$db = $database->getConnection();

// --- HTTP METHOD HANDLING ---
$method = $_SERVER['REQUEST_METHOD'];

switch ($method) {
    /**
     * GET: Fetches notifications. Can be filtered by user_id.
     */
    case 'GET':
        try {
            // Check if a specific user's notifications are requested from the URL
            $userId = $_GET['userId'] ?? $_GET['user_id'] ?? null;
            
            $sql = "
                SELECT n.*, u.name as user_name, u.email 
                FROM notifications n 
                LEFT JOIN users u ON n.user_id = u.id 
            ";
            
            $params = [];
            // If a userId is provided, add a WHERE clause to the SQL query
            if ($userId) {
                $sql .= " WHERE n.user_id = :user_id";
                $params[':user_id'] = $userId;
            }
            
            $sql .= " ORDER BY n.created_at DESC LIMIT 100";
            
            $stmt = $db->prepare($sql);
            $stmt->execute($params);
            $notifications = $stmt->fetchAll(PDO::FETCH_ASSOC);

            // Add a recipient_type for easier frontend logic
            foreach ($notifications as &$notification) {
                $notification['recipient_type'] = is_null($notification['user_id']) ? 'all' : 'single';
            }
            
            http_response_code(200);
            echo json_encode(['success' => true, 'notifications' => $notifications]);

        } catch (PDOException $e) {
            http_response_code(500);
            echo json_encode(['success' => false, 'error' => 'Database error: ' . $e->getMessage()]);
        }
        break;

    /**
     * POST: Creates a new notification.
     * Can send to a single user or all users.
     */
    case 'POST':
        $data = json_decode(file_get_contents('php://input'), true);
        
        if (!isset($data['title']) || !isset($data['message']) || !isset($data['type'])) {
            http_response_code(400);
            echo json_encode(['success' => false, 'error' => 'Required fields are missing: title, message, and type']);
            exit;
        }

        $db->beginTransaction();
        try {
            // Check if the notification is for all users
            if (isset($data['recipient_type']) && $data['recipient_type'] === 'all') {
                // Get all user IDs from the database
                $userStmt = $db->prepare("SELECT id FROM users");
                $userStmt->execute();
                $users = $userStmt->fetchAll(PDO::FETCH_ASSOC);

                if (empty($users)) {
                    throw new Exception("No users found to send notifications to.");
                }

                $stmt = $db->prepare("INSERT INTO notifications (user_id, title, message, type) VALUES (:user_id, :title, :message, :type)");

                // Loop through all users and insert a notification for each
                foreach ($users as $user) {
                    $stmt->execute([
                        ':user_id' => $user['id'],
                        ':title' => $data['title'],
                        ':message' => $data['message'],
                        ':type' => $data['type']
                    ]);
                }
                $message = 'Notification sent to all users successfully';

            } else {
                // Send to a single, specific user
                if (!isset($data['user_id'])) {
                    http_response_code(400);
                    echo json_encode(['success' => false, 'error' => 'User ID is required for individual notifications']);
                    $db->rollBack();
                    exit;
                }
                
                $stmt = $db->prepare("INSERT INTO notifications (user_id, title, message, type) VALUES (:user_id, :title, :message, :type)");
                $stmt->execute([
                    ':user_id' => $data['user_id'],
                    ':title' => $data['title'],
                    ':message' => $data['message'],
                    ':type' => $data['type']
                ]);
                $message = 'Notification sent successfully';
            }
            
            $db->commit();
            http_response_code(201);
            echo json_encode(['success' => true, 'message' => $message]);

        } catch (Exception $e) {
            $db->rollBack();
            http_response_code(500);
            echo json_encode(['success' => false, 'error' => 'Failed to create notification(s): ' . $e->getMessage()]);
        }
        break;

    /**
     * PUT: Updates a notification (e.g., mark as read).
     */
    case 'PUT':
        $data = json_decode(file_get_contents('php://input'), true);
        
        if (!isset($data['id'])) {
            http_response_code(400);
            echo json_encode(['success' => false, 'error' => 'Notification ID is required']);
            exit;
        }
        
        try {
            $sql = "UPDATE notifications SET read_status = :read_status WHERE id = :id";
            $stmt = $db->prepare($sql);
            
            // Default to marking as read (1) if not specified
            $read_status = isset($data['read_status']) ? (int)$data['read_status'] : 1;
            
            $stmt->execute([':read_status' => $read_status, ':id' => $data['id']]);

            http_response_code(200);
            echo json_encode(['success' => true, 'message' => 'Notification updated successfully']);

        } catch (PDOException $e) {
            http_response_code(500);
            echo json_encode(['success' => false, 'error' => 'Failed to update notification: ' . $e->getMessage()]);
        }
        break;

    /**
     * DELETE: Deletes a notification.
     */
    case 'DELETE':
        $id = $_GET['id'] ?? null;
        
        if (!$id) {
            http_response_code(400);
            echo json_encode(['success' => false, 'error' => 'Notification ID is required in the URL.']);
            exit;
        }
        
        try {
            $stmt = $db->prepare("DELETE FROM notifications WHERE id = :id");
            $stmt->bindParam(':id', $id);
            $stmt->execute();
            
            if ($stmt->rowCount() > 0) {
                http_response_code(200);
                echo json_encode(['success' => true, 'message' => 'Notification deleted successfully']);
            } else {
                http_response_code(404);
                echo json_encode(['success' => false, 'error' => 'Notification not found.']);
            }
        } catch (PDOException $e) {
            http_response_code(500);
            echo json_encode(['success' => false, 'error' => 'Database error on delete: ' . $e->getMessage()]);
        }
        break;

    default:
        http_response_code(405);
        echo json_encode(['success' => false, 'error' => 'Method not allowed']);
        break;
}
?>
