<?php

namespace App\Controllers;

use App\Models\ExpedientCounter;
use App\Models\Modality;
use App\Models\Setting;

class SettingController extends BaseController
{
    public function __construct() {
        if (session_status() === PHP_SESSION_NONE) {
            session_start();
        }
    }

    public function index()
    {
        $settings = Setting::getActives();
        $this->render('settings/basic-settings-index', ['settings' => $settings]);
    }

    public function show($id)
    {
        $setting = Setting::find($id);
        $this->render('settings/basic-settings-show', ['setting' => $setting]);
    }

    public function create()
    {
        $this->render('settings/basic-settings-create'); 
    }

    public function edit($id)
    {
        $setting = Setting::find($id);
        if (!$setting) {
            $_SESSION['message'] = "Error: Configuración no encontrada.";
            $_SESSION['message_type'] = "danger";
            header("Location: " . BASE_HEADER . "settings");
            exit;
        }
        $this->render('settings/basic-settings-edit', ['setting' => $setting]);
    }

    public function store()
    {
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $value = $_POST['setting_value'] ?? '';
            $description = $_POST['description'] ?? '';
    
            if (empty($value) || empty($description)) {
                $_SESSION['message'] = "Error: Todos los campos son obligatorios.";
                $_SESSION['message_type'] = "danger";
                header("Location: " . BASE_HEADER . "settings/create");
                exit;
            }
    
            $setting = new Setting();
            $setting->value = $value;
            $setting->description = $description;
            $setting->save();
    
            $_SESSION['message'] = "¡Configuración establecida exitosamente!";
            $_SESSION['message_type'] = "success";
            header("Location: " . BASE_HEADER . "settings");
            exit;
        }
    }

    public function update($id)
    {
        if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['_method']) && $_POST['_method'] === 'PUT') {
            $setting = Setting::find($id);
    
            if (!$setting) {
                $_SESSION['message'] = "Error: Configuración no encontrada.";
                $_SESSION['message_type'] = "danger";
                header("Location: " . BASE_HEADER . "settings");
                exit;
            }
    
            $setting->value = $_POST['setting_value'] ?? '';
            $setting->description = $_POST['description'] ?? '';
    
            if (empty($setting->value) || empty($setting->description)) {
                $_SESSION['message'] = "Error: Todos los campos son obligatorios.";
                $_SESSION['message_type'] = "danger";
                header("Location: " . BASE_HEADER . "settings/$id/edit");
                exit;
            }
    
            $setting->save();
            $_SESSION['message'] = "¡Configuración actualizada exitosamente!";
            $_SESSION['message_type'] = "success";
    
            header("Location: " . BASE_HEADER . "settings");
            exit;
        }
        die("Error: Método no permitido.");
    }

    public function delete($id)
    {
        if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['_method']) && $_POST['_method'] === 'DELETE') {
            $setting = Setting::find($id);
            
            if (!$setting) {
                $_SESSION['message'] = "Error: No se pudo eliminar la configuración.";
                $_SESSION['message_type'] = "danger";
                header("Location: " . BASE_HEADER . "settings");
                exit;
            }

            $setting->delete($setting->id);
            $_SESSION['message'] = "¡Configuración eliminada exitosamente!";
            $_SESSION['message_type'] = "success";
            header("Location: " . BASE_HEADER . "settings");
            exit;
        }
        die("Error: Método no permitido.");
    }

    public function indexExpedientCounter()
    {
        $expedientCountersList = ExpedientCounter::getAll();
        $expedientCounters = [];

        foreach ($expedientCountersList as $counter) {
            $expedientCounters[$counter->modality_id] = $counter;
        }

        $modalities = Modality::getActives();

        $this->render('settings/expedient_counters', [
            'expedientCounters' => $expedientCounters,
            'modalities' => $modalities
        ]);
    }

    public function updateExpedientCounter()
    {
        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            $startNumbers = $_POST['start_number'] ?? [];

            foreach ($startNumbers as $modalityId => $startNumber) {
                $startNumber = (int)$startNumber;
                $counter = ExpedientCounter::findBy('modality_id',$modalityId);

                if ($counter) {
                    $counter->start_number = $startNumber;
                } else {
                    $counter = new ExpedientCounter();
                    $counter->modality_id = $modalityId;
                    $counter->start_number = $startNumber;
                    $counter->current_number = 0;
                }

                $counter->save();
            }

            $_SESSION['message'] = "¡Números iniciales establecidos exitosamente!";
            $_SESSION['message_type'] = "success";
            header("Location: " . BASE_HEADER . "settings/expedient-counters");
            exit;
        }
    }

    public function resetExpedientCounters()
    {
        $counters = ExpedientCounter::getActives();

        foreach ($counters as $counter) {
            $counter->current_number = 0;
            $counter->start_number = 1;
            $counter->save();
        }

        $_SESSION['message'] = "¡Numeración reiniciada exitosamente!";
        $_SESSION['message_type'] = "success";
        header("Location: " . BASE_HEADER . "settings/expedient-counters");
        exit;
    }


}