<?php
namespace App\Controllers;

class SettingsController extends BaseController
{
    private array $tabs = ['branding','regional','numbering','tax','invoice_defaults','quote_defaults','job_defaults','schedule','stripe','roles','users','notifications','billing'];

    public function index()
    {
        return redirect()->to('/fieldly/public/index.php/settings/branding');
    }

    public function tab(string $tab)
    {
        if (!$this->can('view_settings')) return redirect()->to('/fieldly/public/index.php/dashboard')->with('error','Access denied');
        if (!in_array($tab,$this->tabs)) $tab='branding';
        $db = db_connect();
        $cid = $this->companyId;

        $data = ['tab'=>$tab,'settings'=>$this->settings,'tabs'=>$this->tabs];

        if ($tab==='users') {
            $data['users']=$db->table('users u')->select('u.*, r.name as role_name, r.color as role_color')->join('roles r','r.id=u.role_id')->where('u.company_id',$cid)->where('u.deleted_at IS NULL',null,false)->orderBy('u.first_name')->get()->getResultArray();
            $data['roles']=$db->table('roles')->where('company_id',$cid)->orderBy('sort_order')->get()->getResultArray();
        }
        if ($tab==='roles') {
            $data['roles']=$db->table('roles')->where('company_id',$cid)->orderBy('sort_order')->get()->getResultArray();
            foreach ($data['roles'] as &$r) $r['permissions']=array_column($db->table('role_permissions')->where('role_id',$r['id'])->get()->getResultArray(),'permission');
            $data['allPermissions']=config('Fieldly')->permissions;
            $data['permissionGroups']=config('Fieldly')->permissionGroups;
        }
        if ($tab==='tax') {
            $data['taxRates']=$db->table('tax_rates')->where('company_id',$cid)->orderBy('rate','DESC')->get()->getResultArray();
        }
        if ($tab==='schedule') {
            $data['users']=$db->table('users')->where('company_id',$cid)->where('status','active')->where('deleted_at IS NULL',null,false)->get()->getResultArray();
            $userId=$this->request->getGet('user_id')??$this->userId;
            $data['selectedUser']=$userId;
            $data['workingHours']=$db->table('working_hours')->where('company_id',$cid)->where('user_id',$userId)->get()->getResultArray();
            $data['leave']=$db->table('leave_entries')->where('company_id',$cid)->where('user_id',$userId)->orderBy('start_date','DESC')->get()->getResultArray();
        }

        return $this->view('settings/index', $data);
    }

    public function save(string $tab)
    {
        if (!$this->can('view_settings')) return redirect()->back()->with('error','Access denied');
        $post = $this->request->getPost();
        $m    = model('CompanySettingModel');

        $groupMap = ['branding'=>'branding','regional'=>'regional','numbering'=>'numbering','tax'=>'tax','invoice_defaults'=>'invoice_defaults','quote_defaults'=>'quote_defaults','job_defaults'=>'job_defaults','stripe'=>'stripe','notifications'=>'notifications'];

        if (isset($groupMap[$tab])) {
            foreach ($post as $key=>$value) {
                if (!in_array($key,['csrf_token_name','csrf_token'])) {
                    $m->saveSetting($this->companyId,$groupMap[$tab],$key,is_array($value)?json_encode($value):$value);
                }
            }
            session()->set('settings',$m->getAllForCompany($this->companyId));
        }

        return redirect()->to("/fieldly/public/index.php/settings/{$tab}")->with('success','Settings saved.');
    }

    public function createUser()
    {
        if (!$this->can('manage_users')) return redirect()->back()->with('error','Access denied');
        $post = $this->request->getPost();
        if (!$this->validate(['first_name'=>'required','last_name'=>'required','email'=>'required|valid_email','role_id'=>'required|integer','password'=>'required|min_length[8]'])) {
            return redirect()->back()->withInput()->with('errors',$this->validator->getErrors());
        }
        db_connect()->table('users')->insert([
            'company_id'    => $this->companyId,
            'role_id'       => (int)$post['role_id'],
            'first_name'    => trim($post['first_name']),
            'last_name'     => trim($post['last_name']),
            'email'         => trim($post['email']),
            'password_hash' => password_hash($post['password'],PASSWORD_DEFAULT),
            'hourly_rate'   => (float)($post['hourly_rate']??0),
            'color'         => $post['color']??'#4f46e5',
            'initials'      => strtoupper(substr($post['first_name'],0,1).substr($post['last_name'],0,1)),
            'status'        => 'active',
            'created_at'    => date('Y-m-d H:i:s'),
            'updated_at'    => date('Y-m-d H:i:s'),
        ]);
        return redirect()->to('/fieldly/public/index.php/settings/users')->with('success','User created.');
    }

    public function updateUser(int $id)
    {
        if (!$this->can('manage_users')) return redirect()->back()->with('error','Access denied');
        $post = $this->request->getPost();
        $upd  = [
            'role_id'    => (int)$post['role_id'],
            'first_name' => trim($post['first_name']),
            'last_name'  => trim($post['last_name']),
            'email'      => trim($post['email']),
            'hourly_rate'=> (float)($post['hourly_rate']??0),
            'status'     => $post['status']??'active',
            'updated_at' => date('Y-m-d H:i:s'),
        ];
        if (!empty($post['password'])) $upd['password_hash'] = password_hash($post['password'],PASSWORD_DEFAULT);
        db_connect()->table('users')->where('id',$id)->update($upd);
        return redirect()->to('/fieldly/public/index.php/settings/users')->with('success','User updated.');
    }

    public function deleteUser(int $id)
    {
        if (!$this->can('manage_users')) return redirect()->back()->with('error','Access denied');
        if ($id===$this->userId) return redirect()->back()->with('error','Cannot delete yourself.');
        db_connect()->table('users')->where('id',$id)->update(['deleted_at'=>date('Y-m-d H:i:s'),'status'=>'inactive']);
        return redirect()->to('/fieldly/public/index.php/settings/users')->with('success','User deactivated.');
    }

    public function createRole()
    {
        if (!$this->can('manage_roles')) return redirect()->back()->with('error','Access denied');
        $post = $this->request->getPost();
        $db   = db_connect();
        $db->table('roles')->insert(['company_id'=>$this->companyId,'name'=>trim($post['name']),'color'=>$post['color']??'#6b7280','is_default'=>0,'is_system'=>0,'sort_order'=>99,'created_at'=>date('Y-m-d H:i:s'),'updated_at'=>date('Y-m-d H:i:s')]);
        $id = $db->insertID();
        if (!empty($post['permissions'])) {
            foreach ((array)$post['permissions'] as $p) {
                $db->table('role_permissions')->insert(['role_id'=>$id,'permission'=>$p]);
            }
        }
        return redirect()->to('/fieldly/public/index.php/settings/roles')->with('success','Role created.');
    }

    public function updateRole(int $id)
    {
        if (!$this->can('manage_roles')) return redirect()->back()->with('error','Access denied');
        $post = $this->request->getPost();
        $db   = db_connect();
        $db->table('roles')->where('id',$id)->update(['name'=>trim($post['name']),'color'=>$post['color']??'#6b7280','updated_at'=>date('Y-m-d H:i:s')]);
        $db->table('role_permissions')->where('role_id',$id)->delete();
        if (!empty($post['permissions'])) {
            foreach (array_unique(array_filter((array)$post['permissions'])) as $p) {
                $db->table('role_permissions')->insert(['role_id'=>$id,'permission'=>$p]);
            }
        }
        return redirect()->to('/fieldly/public/index.php/settings/roles')->with('success','Role updated.');
    }

    public function deleteRole(int $id)
    {
        if (!$this->can('manage_roles')) return redirect()->back()->with('error','Access denied');
        $db   = db_connect();
        $role = $db->table('roles')->where('id',$id)->get()->getRowArray();
        if ($role && $role['is_system']) return redirect()->back()->with('error','Cannot delete system roles.');
        $db->table('role_permissions')->where('role_id',$id)->delete();
        $db->table('roles')->where('id',$id)->delete();
        return redirect()->to('/fieldly/public/index.php/settings/roles')->with('success','Role deleted.');
    }

    public function createTaxRate()
    {
        if (!$this->can('view_settings')) return redirect()->back()->with('error','Access denied');
        $post = $this->request->getPost();
        db_connect()->table('tax_rates')->insert(['company_id'=>$this->companyId,'name'=>trim($post['name']),'rate'=>(float)$post['rate'],'is_default'=>0,'active'=>1]);
        return redirect()->to('/fieldly/public/index.php/settings/tax')->with('success','Tax rate added.');
    }

    public function deleteTaxRate(int $id)
    {
        if (!$this->can('view_settings')) return redirect()->back()->with('error','Access denied');
        db_connect()->table('tax_rates')->where('id',$id)->delete();
        return redirect()->to('/fieldly/public/index.php/settings/tax')->with('success','Tax rate deleted.');
    }
}