<?php

namespace App\Controllers\View;

use App\Controllers\BaseController;
use App\Models\PreferencesModel;

class PreferencesController extends BaseController
{
    protected $preferencesModel;

    public function __construct()
    {
        $this->preferencesModel = new PreferencesModel();
    }

    /**
     * Display preferences page
     * GET /preferences/{userId}
     */
    public function index($userId = null)
    {
        // Get user ID from parameter or session
        $userId = $userId ?? (int) session()->get('user_id');
        
        if (!$userId) {
            return redirect()->to('/login')->with('error', 'Please log in to view preferences');
        }

        // Fetch preferences for the current user
        $preferences = $this->preferencesModel->where('user_id', $userId)->first();

        // If preferences do not exist, set default preferences
        if (!$preferences) {
            $preferences = [
                'receive_email_notifications' => 1,
                'receive_sms_notifications'   => 1,
                'theme'                       => 'light',
                'language'                    => 'en',
            ];
        }

        // Append style/menu selections from session or defaults
        $styleConfig = config('Style');
        $preferences['style_color'] = $preferences['style_color'] ?? (session()->get('style_color') ?? ($styleConfig->defaultStyle ?? 'blue'));
        $preferences['menu_color']  = $preferences['menu_color']  ?? (session()->get('menu_color')  ?? ($styleConfig->defaultMenu  ?? 'white'));

        // Options for selectors
        $styleOptions = array_keys($styleConfig->stylePalettes ?? []);
        $menuOptions  = array_keys($styleConfig->menuPalettes ?? []);

        // Load the view with the user's preferences
        return view('/preferences', [
            'preferences'  => $preferences,
            'styleOptions' => $styleOptions,
            'menuOptions'  => $menuOptions,
            'userId'       => $userId,
        ]);
    }

    /**
     * Update preferences
     * POST /preferences/update/{userId}
     */
    public function updatePreferences($userId = null)
    {
        // Get user ID from parameter or session
        $userId = $userId ?? (int) session()->get('user_id');
        
        if (!$userId) {
            return redirect()->to('/login')->with('error', 'Please log in to update preferences');
        }

        // Validation rules
        $validation = \Config\Services::validation();

        $styleConfig = config('Style');
        $styleOptions = implode(',', array_keys($styleConfig->stylePalettes ?? []));
        $menuOptions = implode(',', array_keys($styleConfig->menuPalettes ?? []));

        $validation->setRules([
            'receive_email_notifications' => 'permit_empty|in_list[0,1]',
            'receive_sms_notifications'   => 'permit_empty|in_list[0,1]',
            'theme'                       => 'permit_empty|in_list[light,dark]',
            'language'                    => 'permit_empty|in_list[en,fr,es]',
            'style_color'                 => $styleOptions ? 'permit_empty|in_list[' . $styleOptions . ']' : 'permit_empty',
            'menu_color'                  => $menuOptions ? 'permit_empty|in_list[' . $menuOptions . ']' : 'permit_empty',
        ]);

        if (!$validation->run($this->request->getPost())) {
            $preferences = $this->preferencesModel->where('user_id', $userId)->first();
            if (!$preferences) {
                $preferences = [
                    'receive_email_notifications' => 1,
                    'receive_sms_notifications'   => 1,
                    'theme'                       => 'light',
                    'language'                    => 'en',
                ];
            }
            $preferences['style_color'] = $this->request->getPost('style_color') ?? ($preferences['style_color'] ?? (session()->get('style_color') ?? ($styleConfig->defaultStyle ?? 'blue')));
            $preferences['menu_color']  = $this->request->getPost('menu_color')  ?? ($preferences['menu_color'] ?? (session()->get('menu_color')  ?? ($styleConfig->defaultMenu  ?? 'white')));

            return view('/preferences', [
                'preferences'  => $preferences,
                'styleOptions' => array_keys($styleConfig->stylePalettes ?? []),
                'menuOptions'  => array_keys($styleConfig->menuPalettes ?? []),
                'validation'   => $validation,
                'userId'       => $userId,
            ]);
        }

        // Prepare updated data (map form fields to database fields)
        $updateData = [
            'receive_email_notifications' => $this->request->getPost('receive_email_notifications') ?? $this->request->getPost('notification_email') ?? 1,
            'receive_sms_notifications'   => $this->request->getPost('receive_sms_notifications') ?? $this->request->getPost('notification_sms') ?? 1,
            'theme'                       => $this->request->getPost('theme') ?? 'light',
            'language'                    => $this->request->getPost('language') ?? 'en',
        ];

        // Store style/menu selections in session (no DB column dependency)
        $styleColor = $this->request->getPost('style_color');
        $menuColor = $this->request->getPost('menu_color');
        if ($styleColor && isset(($styleConfig->stylePalettes ?? [])[$styleColor])) {
            session()->set('style_color', $styleColor);
            $updateData['style_color'] = $styleColor;
        }
        if ($menuColor && isset(($styleConfig->menuPalettes ?? [])[$menuColor])) {
            session()->set('menu_color', $menuColor);
            $updateData['menu_color'] = $menuColor;
        }

        // Check if preferences already exist, update if they do, otherwise insert new preferences
        $existing = $this->preferencesModel->where('user_id', $userId)->first();
        if ($existing) {
            $this->preferencesModel->update($existing['id'], $updateData);
        } else {
            $updateData['user_id'] = $userId;
            $this->preferencesModel->insert($updateData);
        }

        // Redirect back to preferences page with success message
        return redirect()->to('/preferences/' . $userId)->with('success', 'Preferences updated successfully');
    }
}
