<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;

class NotificationController extends Controller
{
    /**
     * Get all notifications from the database for the authenticated user.
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
public function getNotifications(Request $request)
{
    // Ensure the user is authenticated
    $user = Auth::user();

    if (!$user) {
        return response()->json(['error' => 'Unauthenticated'], 401);
    }

    // Get the 'status' query parameter with a default of 'read'
    $status = $request->query('status', 'read'); // Default to 'read' if 'status' is not provided

    // Determine the condition for read/unread notifications
    $readCondition = $status === 'unread' ? 0 : 1;

    // Fetch notifications for the authenticated user based on the 'status' filter
    $notifications = DB::select('
        SELECT `id`, `user_id`, `order_id`, `message`, `read`, `created_at`, `updated_at`
        FROM `notifications`
        WHERE `user_id` = ? AND `read` = ?
    ', [$user->user_id, $readCondition]);

    // If no notifications are found, return a response indicating this
    if (empty($notifications)) {
        return response()->json([
            'message' => 'No notifications found',
        ], 200);
    }

    // If unread notifications are fetched, mark them as read
    if ($readCondition === 0) {
        $unreadNotificationIds = array_filter(
            array_map(function ($notification) {
                return $notification->read == 0 ? $notification->id : null;
            }, $notifications)
        );

        if (!empty($unreadNotificationIds)) {
            // Update only unread notifications
            DB::update(
                'UPDATE `notifications` SET `read` = 1 WHERE `id` IN (' . implode(',', $unreadNotificationIds) . ') AND `read` = 0'
            );
        }
    }

    // Format notifications with subject, message, and time
    $formattedNotifications = array_map(function ($notification) {
        $message = $notification->message;

        // Append order_id to the message if it exists
        if (!empty($notification->order_id)) {
            $message .= " (Order ID: {$notification->order_id})";
        }

        return [
            'id' => $notification->id,
            'user_id' => $notification->user_id,
            'order_id' => $notification->order_id,
            'subject' => $this->generateSubject($notification->message), // Generate subject
            'message' => $message,
            'time' => $notification->created_at,
            'read' => $notification->read == 0 ? 'Not Read' : 'Read', // Reflect the original read status
        ];
    }, $notifications);

    // Return the formatted notifications
    return response()->json([
        'notifications' => $formattedNotifications,
    ], 200);
}

    /**
     * Generate a subject based on the content of the message.
     *
     * @param string $message
     * @return string
     */
    private function generateSubject($message)
    {
        // Check if the message contains the phrase 'Order status updated'
        if (str_contains($message, 'Order #') && str_contains($message, 'status updated')) {
            return 'Order Status Updated';
        }

        if (str_contains($message, 'Order shipped')) {
            return 'Order Shipped';
        }

        if (str_contains($message, 'New order placed')) {
            return 'New Order Placed';
        }

        // Default subject if no specific condition is matched
        return 'New Notification';
    }

    /**
     * Delete a notification by its ID for the authenticated user.
     *
     * @param Request $request
     * @param int $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function deleteNotification(Request $request, $id)
    {
        // Ensure the user is authenticated
        $user = Auth::user();

        if (!$user) {
            return response()->json(['error' => 'Unauthenticated'], 401);
        }

        // Verify if the notification belongs to the authenticated user
        $notification = DB::selectOne('
            SELECT `id`, `user_id`
            FROM `notifications`
            WHERE `id` = ? AND `user_id` = ?
        ', [$id, $user->user_id]);

        if (!$notification) {
            return response()->json(['error' => 'Notification not found or unauthorized'], 404);
        }

        // Delete the notification
        DB::delete('DELETE FROM `notifications` WHERE `id` = ?', [$id]);

        return response()->json(['message' => 'Notification deleted successfully'], 200);
    }

    /**
     * Mark a notification as read by its ID.
     *
     * @param Request $request
     * @param int $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function markAsRead(Request $request, $id)
    {
        // Ensure the user is authenticated
        $user = Auth::user();

        if (!$user) {
            return response()->json(['error' => 'Unauthenticated'], 401);
        }

        // Verify if the notification belongs to the authenticated user
        $notification = DB::selectOne('
            SELECT `id`, `user_id`, `read`
            FROM `notifications`
            WHERE `id` = ? AND `user_id` = ?
        ', [$id, $user->user_id]);

        if (!$notification) {
            return response()->json(['error' => 'Notification not found or unauthorized'], 404);
        }

        // Update the notification status to read (1)
        DB::update('UPDATE `notifications` SET `read` = 1 WHERE `id` = ?', [$id]);

        return response()->json(['message' => 'Notification marked as read'], 200);
    }
}
