<?php

namespace App\Controllers;

use App\Controllers\BaseController;

class Auth extends BaseController
{
    protected $userModel;
    protected $districtModel;

    public function __construct()
    {
        helper(['form', 'url']);
        $this->userModel = new \App\Models\UserModel();
        $this->districtModel = new \App\Models\DistrictModel();
    }

    public function index()
    {
        // Generate initial captcha
        $this->generateCaptcha();
        
        // Get dynamic data for dropdowns
        $data = [
            'userTypes' => $this->userModel->findAll(),
            'districts' => $this->districtModel->where('State_code', 13)->orderBy('District_Name', 'ASC')->findAll()
        ];
        
        return view('login', $data);
    }

    public function login()
    {
        $validation = \Config\Services::validation();
        
        $validation->setRules([
            'user_type' => 'required',
            'district'  => 'required',
            'password'  => 'required|min_length[6]',
            'captcha'   => 'required'
        ]);

        if (!$validation->withRequest($this->request)->run()) {
            return redirect()->back()->withInput()->with('error', 'Please fill all required fields correctly.');
        }

        $userTypeId = $this->request->getPost('user_type');
        $districtCode = $this->request->getPost('district');
        $password = $this->request->getPost('password');
        $captcha = $this->request->getPost('captcha');
        $sessionCaptcha = session('captcha_code');

        // Verify captcha
        if (strtoupper($captcha) !== strtoupper($sessionCaptcha)) {
            $this->generateCaptcha(); // Generate new captcha
            return redirect()->back()->withInput()->with('error', 'Invalid captcha code.');
        }

        // Get user type and district details from database
        $db = \Config\Database::connect();
        
        $userTypeQuery = $db->table('tbl_type_user')->where('id', $userTypeId)->get()->getRowArray();
        $districtQuery = $db->table('tbl_district_master')
            ->where('District_code', $districtCode)
            ->where('State_code', 13)
            ->get()->getRowArray();

        if (!$userTypeQuery || !$districtQuery) {
            $this->generateCaptcha(); // Generate new captcha
            return redirect()->back()->withInput()->with('error', 'Invalid user type or district selected.');
        }

        // Here you would typically verify credentials against a users table
        // For now, let's use dummy credentials based on user type
        $validCredentials = [
            'Admin' => ['password' => 'admin123'],
            'District Officer' => ['password' => 'district123'],
            'Block Officer' => ['password' => 'block123'],
            'Supervisor' => ['password' => 'supervisor123'],
            'Data Entry Operator' => ['password' => 'dataentry123'],
            'Field Worker' => ['password' => 'fieldworker123']
        ];

        if (isset($validCredentials[$userTypeQuery['type_user']]) && $validCredentials[$userTypeQuery['type_user']]['password'] === $password) {
            // Set session data
            $sessionData = [
                'user_id' => $userTypeQuery['id'],
                'user_type_id' => $userTypeQuery['id'],
                'user_type' => $userTypeQuery['type_user'],
                'user_role' => $userTypeQuery['role'],
                'district_code' => $districtQuery['District_code'],
                'district_name' => $districtQuery['District_Name'],
                'state_code' => $districtQuery['State_code'],
                'logged_in' => true
            ];
            
            session()->set($sessionData);
            
            // Redirect based on user role
            switch ($userTypeQuery['role']) {
                case 1: // Admin
                    return redirect()->to('/admin/dashboard');
                case 2: // District Officer
                    return redirect()->to('/district/dashboard');
                case 3: // Block Officer
                    return redirect()->to('/block/dashboard');
                case 4: // Supervisor
                    return redirect()->to('/supervisor/dashboard');
                default:
                    return redirect()->to('/dashboard');
            }
        } else {
            $this->generateCaptcha(); // Generate new captcha
            return redirect()->back()->withInput()->with('error', 'Invalid credentials.');
        }
    }

    public function logout()
    {
        session()->destroy();
        return redirect()->to('/auth');
    }

    public function refreshCaptcha()
    {
        $input = json_decode($this->request->getBody(), true);
        if (isset($input['captcha'])) {
            session()->set('captcha_code', $input['captcha']);
            return $this->response->setJSON(['status' => 'success']);
        }
        return $this->response->setJSON(['status' => 'error']);
    }

    private function generateCaptcha()
    {
        $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        $captcha = '';
        for ($i = 0; $i < 6; $i++) {
            $captcha .= $chars[rand(0, strlen($chars) - 1)];
        }
        session()->set('captcha_code', $captcha);
        return $captcha;
    }
}