<?php

namespace App\Http\Controllers\Api\Admin;

use App\Http\Controllers\Api\ApiController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;

class SettingController extends ApiController
{
    /**
     * Get all system settings
     */
    public function index(Request $request)
    {
        $category = $request->get('category'); // general, academic, fee, notification, etc.

        // TODO: Create settings table if not exists
        // For now, return sample settings structure

        $settings = [
            'general' => [
                'school_name' => config('app.name', 'School ERP System'),
                'school_code' => 'SCH001',
                'email' => 'info@school.com',
                'phone' => '+1234567890',
                'address' => '123 School Street',
                'website' => 'https://school.com',
                'timezone' => config('app.timezone', 'UTC'),
                'date_format' => 'Y-m-d',
                'time_format' => 'H:i:s',
                'currency' => 'USD',
                'currency_symbol' => '$',
            ],
            'academic' => [
                'academic_year_start_month' => 'April',
                'academic_year_end_month' => 'March',
                'attendance_type' => 'daily', // daily, period
                'enable_online_classes' => true,
                'enable_homework' => true,
                'enable_examination' => true,
                'passing_marks_percentage' => 40,
            ],
            'fee' => [
                'enable_online_payment' => true,
                'late_fee_applicable' => true,
                'late_fee_type' => 'fixed', // fixed, percentage
                'late_fee_amount' => 50,
                'fee_due_date_buffer_days' => 7,
                'payment_methods' => ['cash', 'cheque', 'online', 'card', 'upi'],
            ],
            'notification' => [
                'enable_sms_notification' => true,
                'enable_email_notification' => true,
                'enable_push_notification' => false,
                'notify_attendance' => true,
                'notify_exam_results' => true,
                'notify_fee_due' => true,
                'notify_announcements' => true,
            ],
            'attendance' => [
                'attendance_start_time' => '08:00',
                'attendance_end_time' => '16:00',
                'late_arrival_threshold_minutes' => 15,
                'mark_absent_after_minutes' => 30,
                'weekend_days' => ['Saturday', 'Sunday'],
            ],
            'security' => [
                'enable_two_factor_auth' => false,
                'password_expiry_days' => 90,
                'session_timeout_minutes' => 30,
                'max_login_attempts' => 5,
                'enable_ip_whitelist' => false,
            ],
            'library' => [
                'max_books_per_student' => 3,
                'book_issue_duration_days' => 14,
                'enable_fine_for_late_return' => true,
                'fine_per_day' => 5,
            ],
            'hostel' => [
                'enable_hostel' => true,
                'visitor_allowed_days' => ['Saturday', 'Sunday'],
                'visitor_allowed_time' => '10:00-18:00',
            ],
            'transport' => [
                'enable_transport' => true,
                'enable_gps_tracking' => false,
                'transport_fee_frequency' => 'monthly', // monthly, quarterly, yearly
            ],
        ];

        if ($category && isset($settings[$category])) {
            return $this->successResponse([
                'category' => $category,
                'settings' => $settings[$category],
            ]);
        }

        return $this->successResponse($settings);
    }

    /**
     * Update system settings
     */
    public function update(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'category' => 'required|string|in:general,academic,fee,notification,attendance,security,library,hostel,transport',
            'settings' => 'required|array',
        ]);

        if ($validator->fails()) {
            return $this->errorResponse('Validation failed', 422, $validator->errors());
        }

        try {
            $category = $request->category;
            $settings = $request->settings;

            // TODO: Store in database (create settings table)
            // Setting::updateOrCreate(
            //     ['category' => $category],
            //     ['settings' => json_encode($settings), 'updated_by' => auth('admin')->id()]
            // );

            // Clear cache
            Cache::forget("settings.{$category}");

            // Log the settings update
            DB::table('activity_logs')->insert([
                'user_id' => auth('admin')->id(),
                'action' => 'settings_updated',
                'description' => "Updated {$category} settings",
                'created_at' => now(),
            ]);

            return $this->successResponse([
                'category' => $category,
                'settings' => $settings,
            ], 'Settings updated successfully');

        } catch (\Exception $e) {
            return $this->errorResponse('Failed to update settings: ' . $e->getMessage(), 500);
        }
    }

    /**
     * Reset settings to default
     */
    public function reset(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'category' => 'required|string|in:general,academic,fee,notification,attendance,security,library,hostel,transport',
        ]);

        if ($validator->fails()) {
            return $this->errorResponse('Validation failed', 422, $validator->errors());
        }

        $category = $request->category;

        try {
            // TODO: Reset to default values in database
            // Setting::where('category', $category)->delete();

            // Clear cache
            Cache::forget("settings.{$category}");

            return $this->successResponse(null, "Settings for {$category} reset to default successfully");

        } catch (\Exception $e) {
            return $this->errorResponse('Failed to reset settings: ' . $e->getMessage(), 500);
        }
    }

    /**
     * Get setting by key
     */
    public function show(Request $request, $category, $key)
    {
        // TODO: Fetch from database
        // $setting = Setting::where('category', $category)->first();
        // $settings = json_decode($setting->settings, true);
        // return $settings[$key] ?? null;

        return $this->successResponse([
            'category' => $category,
            'key' => $key,
            'value' => 'Setting value will be fetched from database',
        ]);
    }

    /**
     * Update single setting
     */
    public function updateSingle(Request $request, $category, $key)
    {
        $validator = Validator::make($request->all(), [
            'value' => 'required',
        ]);

        if ($validator->fails()) {
            return $this->errorResponse('Validation failed', 422, $validator->errors());
        }

        try {
            // TODO: Update in database
            // $setting = Setting::where('category', $category)->first();
            // $settings = json_decode($setting->settings, true);
            // $settings[$key] = $request->value;
            // $setting->update(['settings' => json_encode($settings)]);

            Cache::forget("settings.{$category}");

            return $this->successResponse([
                'category' => $category,
                'key' => $key,
                'value' => $request->value,
            ], 'Setting updated successfully');

        } catch (\Exception $e) {
            return $this->errorResponse('Failed to update setting: ' . $e->getMessage(), 500);
        }
    }
}
