<?php

class SettingsController extends Controller
{
    private function editableTextKeys(): array
    {
        return [
            'company_name'      => 'Shop Name',
            'tagline'           => 'Tagline (login page)',
            'company_address'   => 'Address',
            'company_phone'     => 'Phone',
            'company_email'     => 'Email',
            'currency_symbol'   => 'Currency Symbol',
            'timezone'          => 'Timezone',
            'order_number_prefix' => 'Invoice/Order Prefix',
            'receipt_footer_note' => 'Receipt Footer Note',
            'public_base_url'   => 'Public Base URL (for QR codes / tracking links)',
            'bank_account_name'   => 'Bank Account Name (for customer app bank transfer)',
            'bank_name'           => 'Bank Name (for customer app bank transfer)',
            'bank_account_number' => 'Bank Account Number (for customer app bank transfer)',
            'payhere_merchant_id'     => 'PayHere Merchant ID',
            'payhere_merchant_secret' => 'PayHere Merchant Secret',
            'payhere_mode'            => 'PayHere Mode (sandbox or live)',
            'order_open_time'         => 'Order Accepting — Opens At',
            'order_close_time'        => 'Order Accepting — Closes At',
        ];
    }

    public function index(): void
    {
        Auth::requirePermission('settings', 'view');

        $db = Database::getConnection();
        $rows = $db->query("SELECT setting_key, setting_value FROM settings")->fetchAll();
        $current = [];
        foreach ($rows as $row) {
            $current[$row['setting_key']] = $row['setting_value'];
        }

        $userModel = new User();
        $roleModel = new Role();
        $roles = $roleModel->allWithUserCount();

        $permissionMatrices = [];
        foreach ($roles as $r) {
            $permissionMatrices[$r['id']] = $roleModel->permissionMatrix((int) $r['id']);
        }

        $auditLogs = $db->query(
            "SELECT al.*, u.full_name FROM audit_log al
             LEFT JOIN users u ON u.id = al.user_id
             ORDER BY al.id DESC LIMIT 200"
        )->fetchAll();

        $this->view('admin.settings.index', [
            'pageTitle'          => 'System Settings',
            'fields'             => $this->editableTextKeys(),
            'current'            => $current,
            'users'              => $userModel->allWithRole(),
            'roles'              => $roles,
            'permissionMatrices' => $permissionMatrices,
            'auditLogs'          => $auditLogs,
            'csrf'               => $this->csrfField(),
        ]);
    }

    public function save(): void
    {
        Auth::requirePermission('settings', 'edit');
        $this->verifyCsrf();

        $db = Database::getConnection();
        $stmt = $db->prepare(
            "INSERT INTO settings (setting_key, setting_value) VALUES (:k, :v)
             ON DUPLICATE KEY UPDATE setting_value = VALUES(setting_value)"
        );

        foreach (array_keys($this->editableTextKeys()) as $key) {
            $stmt->execute(['k' => $key, 'v' => trim($this->input($key, ''))]);
        }

        // Receipt toggle checkboxes (unchecked box simply won't be present in $_POST)
        $stmt->execute(['k' => 'show_tax_on_receipt', 'v' => $this->input('show_tax_on_receipt') ? '1' : '0']);
        $stmt->execute(['k' => 'show_logo_on_receipt', 'v' => $this->input('show_logo_on_receipt') ? '1' : '0']);
        $stmt->execute(['k' => 'orders_manually_paused', 'v' => $this->input('orders_manually_paused') ? '1' : '0']);

        // Logo upload
        $logoPath = $this->handleImageUpload('logo');
        if ($logoPath) {
            $stmt->execute(['k' => 'logo_path', 'v' => $logoPath]);
        } elseif ((int) $this->input('remove_logo', 0) === 1) {
            $stmt->execute(['k' => 'logo_path', 'v' => '']);
        }

        // Login background upload
        $bgPath = $this->handleImageUpload('login_background');
        if ($bgPath) {
            $stmt->execute(['k' => 'login_background_path', 'v' => $bgPath]);
        } elseif ((int) $this->input('remove_login_background', 0) === 1) {
            $stmt->execute(['k' => 'login_background_path', 'v' => '']);
        }

        AuditLogger::log(Auth::id(), 'SETTINGS_UPDATE', 'settings', 'Updated system settings');
        $this->redirect('admin/settings?tab=shop');
    }

    private function handleImageUpload(string $fieldName): ?string
    {
        if (empty($_FILES[$fieldName]) || $_FILES[$fieldName]['error'] === UPLOAD_ERR_NO_FILE) {
            return null;
        }
        if ($_FILES[$fieldName]['error'] !== UPLOAD_ERR_OK) {
            return null;
        }

        $allowed = ['image/jpeg' => 'jpg', 'image/png' => 'png', 'image/webp' => 'webp', 'image/gif' => 'gif'];
        $mime = mime_content_type($_FILES[$fieldName]['tmp_name']);
        if (!isset($allowed[$mime])) {
            return null;
        }
        if ($_FILES[$fieldName]['size'] > 3 * 1024 * 1024) {
            return null;
        }

        $ext = $allowed[$mime];
        $filename = $fieldName . '_' . bin2hex(random_bytes(8)) . '.' . $ext;
        $uploadDir = ROOT_PATH . '/public/uploads/settings/';
        if (!is_dir($uploadDir)) {
            mkdir($uploadDir, 0755, true);
        }
        if (!move_uploaded_file($_FILES[$fieldName]['tmp_name'], $uploadDir . $filename)) {
            return null;
        }

        return 'uploads/settings/' . $filename;
    }
}
