<?php

declare(strict_types=1);

namespace Admin\Controllers;

/**
 * Admin Settings Controller
 *
 * Manages site-wide settings stored as key-value pairs,
 * grouped by category (General, Stats, Social Media).
 */
class AdminSettingsController extends AdminController
{
    /**
     * Display the settings form.
     *
     * @param array<string, string> $params Route parameters
     * @return void
     */
    public function index(array $params = []): void
    {
        requireAdmin();

        $stmt = $this->db->query('SELECT `setting_key`, `setting_value` FROM `settings`');
        $rows = $stmt->fetchAll() ?: [];

        $settings = [];
        foreach ($rows as $row) {
            $settings[$row['setting_key']] = $row['setting_value'];
        }

        // Define setting groups for the form
        $settingGroups = [
            'General' => [
                'site_name'     => ['label' => 'Site Name', 'type' => 'text'],
                'site_tagline'  => ['label' => 'Site Tagline', 'type' => 'text'],
                'site_email'    => ['label' => 'Site Email', 'type' => 'email'],
                'site_phone'    => ['label' => 'Site Phone', 'type' => 'text'],
                'site_address'  => ['label' => 'Site Address', 'type' => 'textarea'],
                'footer_text'   => ['label' => 'Footer Text', 'type' => 'text'],
                'contact_email' => ['label' => 'Contact Email', 'type' => 'email'],
                'maintenance_mode' => ['label' => 'Maintenance Mode', 'type' => 'select', 'options' => ['0' => 'Off', '1' => 'On']],
            ],
            'Stats' => [
                'stat_total_students'  => ['label' => 'Total Students', 'type' => 'number'],
                'stat_total_courses'   => ['label' => 'Total Courses', 'type' => 'number'],
                'stat_total_branches'  => ['label' => 'Total Branches', 'type' => 'number'],
                'stat_years_experience' => ['label' => 'Years of Experience', 'type' => 'number'],
            ],
            'Social Media' => [
                'social_facebook'  => ['label' => 'Facebook URL', 'type' => 'url'],
                'social_twitter'   => ['label' => 'Twitter/X URL', 'type' => 'url'],
                'social_youtube'   => ['label' => 'YouTube URL', 'type' => 'url'],
                'social_instagram' => ['label' => 'Instagram URL', 'type' => 'url'],
                'social_linkedin'  => ['label' => 'LinkedIn URL', 'type' => 'url'],
            ],
        ];

        $this->adminView('settings', [
            'title'         => 'Site Settings',
            'currentPage'   => 'settings',
            'settings'      => $settings,
            'settingGroups' => $settingGroups,
        ]);
    }

    /**
     * Update all settings at once.
     *
     * @param array<string, string> $params Route parameters
     * @return void
     */
    public function update(array $params = []): void
    {
        requireAdmin();
        $this->validateCsrf();

        $allowedKeys = [
            'site_name', 'site_tagline', 'site_email', 'site_phone', 'site_address',
            'footer_text', 'contact_email', 'maintenance_mode',
            'stat_total_students', 'stat_total_courses', 'stat_total_branches', 'stat_years_experience',
            'social_facebook', 'social_twitter', 'social_youtube', 'social_instagram', 'social_linkedin',
        ];

        $updated = 0;

        foreach ($allowedKeys as $key) {
            if (!isset($_POST[$key])) {
                continue;
            }

            $value = sanitize($_POST[$key]);

            // Use INSERT ... ON DUPLICATE KEY UPDATE for upsert
            $stmt = $this->db->prepare(
                'INSERT INTO `settings` (`setting_key`, `setting_value`)
                 VALUES (:key, :value)
                 ON DUPLICATE KEY UPDATE `setting_value` = :value2'
            );

            $stmt->execute([
                ':key'   => $key,
                ':value' => $value,
                ':value2' => $value,
            ]);

            $updated++;
        }

        flash('success', "Settings updated successfully. ({$updated} settings saved)");
        redirect('/admin/settings');
    }
}
