<?php

declare(strict_types=1);

namespace App\Controllers;

use App\Helpers\ActivityLogger;
use App\Helpers\ImageUploader;
use App\Models\SettingsModel;
use Core\Request;
use Core\Session;

final class SettingsController extends BaseController
{
    private SettingsModel $model;

    public function __construct()
    {
        parent::__construct();
        $this->model = new SettingsModel();
    }

    // ── Show settings ─────────────────────────────────────────────────────────

    public function index(array $params = []): void
    {
        $this->requirePermission('settings.manage');

        $modes = $this->db->fetchAll(
            "SELECT * FROM payment_modes ORDER BY sort_order, id"
        );

        $this->view('settings.index', [
            'pageTitle'    => 'Settings',
            'breadcrumbs'  => ['Settings' => null],
            'settings'     => $this->model->all(),
            'paymentModes' => $modes,
        ]);
    }

    // ── Payment modes ─────────────────────────────────────────────────────────

    public function storePaymentMode(): void
    {
        $this->requirePermission('settings.manage');
        Request::verifyCsrf();
        $name = trim(Request::str('name'));
        if ($name === '') { $this->redirect('/settings'); }
        $max = (int)$this->db->fetchValue("SELECT COALESCE(MAX(sort_order),0) FROM payment_modes");
        $this->db->insert('payment_modes', ['name' => $name, 'sort_order' => $max + 1, 'is_active' => 1]);
        Session::flash('success', "Payment mode '{$name}' added.");
        $this->redirect('/settings#payment-modes');
    }

    public function togglePaymentMode(array $params = []): void
    {
        $this->requirePermission('settings.manage');
        Request::verifyCsrf();
        $id  = (int)($params['id'] ?? 0);
        $cur = (int)$this->db->fetchValue("SELECT is_active FROM payment_modes WHERE id=?", [$id]);
        $this->db->update('payment_modes', ['is_active' => $cur ? 0 : 1], ['id' => $id]);
        $this->json(['ok' => true, 'active' => !$cur]);
    }

    public function deletePaymentMode(array $params = []): void
    {
        $this->requirePermission('settings.manage');
        Request::verifyCsrf();
        $id = (int)($params['id'] ?? 0);
        $this->db->delete('payment_modes', ['id' => $id]);
        $this->json(['ok' => true]);
    }

    // ── Save settings ─────────────────────────────────────────────────────────

    public function update(array $params = []): void
    {
        $this->requirePermission('settings.manage');
        Request::verifyCsrf();

        $map = [
            'restaurant_name'    => trim(Request::str('restaurant_name')),
            'restaurant_phone'   => trim(Request::str('restaurant_phone')),
            'restaurant_address' => trim(Request::str('restaurant_address')),
            'restaurant_lat'     => trim(Request::str('restaurant_lat')),
            'restaurant_lng'     => trim(Request::str('restaurant_lng')),
            'currency_symbol'    => trim(Request::str('currency_symbol', 'Rs.')),
            'tax_rate'           => (string) max(0, (float) Request::str('tax_rate', '0')),
            'min_order_amount'   => (string) max(0, (float) Request::str('min_order_amount', '0')),
            // Delivery policy
            'delivery_charge_type' => in_array(Request::str('delivery_charge_type'), ['fixed','per_km','free'])
                                        ? Request::str('delivery_charge_type') : 'fixed',
            'delivery_fixed_fee'   => (string) max(0, (float) Request::str('delivery_fixed_fee',  '0')),
            'delivery_min_fee'     => (string) max(0, (float) Request::str('delivery_min_fee',     '0')),
            'delivery_per_km_rate' => (string) max(0, (float) Request::str('delivery_per_km_rate', '0')),
            'delivery_free_above'  => (string) max(0, (float) Request::str('delivery_free_above',  '0')),
            // Legacy key kept for backward compat
            'delivery_fee'         => (string) max(0, (float) Request::str('delivery_fixed_fee', '0')),
            'order_alert_sound'    => Request::str('order_alert_sound') === '1' ? '1' : '0',
            'app_maintenance_mode' => Request::str('app_maintenance_mode') === '1' ? '1' : '0',
            'show_rider_location'  => Request::str('show_rider_location') === '1' ? '1' : '0',
            // Delivery range (km from the restaurant; 0 = unlimited)
            'delivery_radius_km'   => (string) max(0, (float) Request::str('delivery_radius_km', '0')),
            // Working hours (HH:MM, 24h). Empty = always open.
            'open_time'            => trim(Request::str('open_time')),
            'close_time'           => trim(Request::str('close_time')),
            // First-order discount policy (applied automatically to a customer's first order)
            'first_order_discount_enabled' => Request::str('first_order_discount_enabled') === '1' ? '1' : '0',
            'first_order_discount_type'    => in_array(Request::str('first_order_discount_type'), ['percentage','fixed'])
                                                ? Request::str('first_order_discount_type') : 'percentage',
            'first_order_discount_value'   => (string) max(0, (float) Request::str('first_order_discount_value', '0')),
            'first_order_min_amount'       => (string) max(0, (float) Request::str('first_order_min_amount', '0')),
            'first_order_max_discount'     => (string) max(0, (float) Request::str('first_order_max_discount', '0')),
        ];

        // Logo upload
        if (!empty($_FILES['restaurant_logo']['name'])) {
            $uploader = new ImageUploader('uploads');
            $result   = $uploader->upload($_FILES['restaurant_logo'], 'logo');
            if ($result['success']) {
                $map['restaurant_logo'] = $result['filename'];
            } else {
                Session::flash('error', 'Logo upload failed: ' . $result['error']);
                $this->redirect('/settings');
            }
        }

        if (empty($map['restaurant_name'])) {
            Session::flash('error', 'Restaurant name is required.');
            $this->redirect('/settings');
        }

        $this->model->bulkSet($map);
        SettingsModel::clearCache();

        ActivityLogger::updated('Settings', 0, 'app settings');
        Session::flash('success', 'Settings saved successfully.');
        $this->redirect('/settings');
    }
}
