<?php
namespace App\Controllers;

class GlobalController extends BaseController
{
    public function index() { return redirect()->to('/fieldly/public/index.php/global/job-types'); }

    public function tab(string $tab)
    {
        if (!$this->can('view_global_settings')) return redirect()->to('/')->with('error','Access denied');
        $db=$db=db_connect(); $cid=$this->companyId;
        $data=['tab'=>$tab];

        if ($tab==='job-types')   $data['jobTypes']=$db->table('job_types')->where('company_id',$cid)->orderBy('sort_order')->get()->getResultArray();
        if ($tab==='statuses')    $data['jobStatuses']=$db->table('job_statuses')->where('company_id',$cid)->orderBy('sort_order')->get()->getResultArray();
        if ($tab==='pricing')     $data['pricingTypes']=$db->table('pricing_types')->where('company_id',$cid)->orderBy('sort_order')->get()->getResultArray();
        if ($tab==='templates')   {
            $data['templates']=$db->table('checklist_templates')->where('company_id',$cid)->get()->getResultArray();
            foreach ($data['templates'] as &$t) $t['items']=$db->table('checklist_template_items')->where('template_id',$t['id'])->orderBy('sort_order')->get()->getResultArray();
            $data['jobTypes']=$db->table('job_types')->where('company_id',$cid)->where('active',1)->get()->getResultArray();
        }
        if (in_array($tab,['customer-fields','job-fields','quote-fields','invoice-fields'])) {
            $entityMap=['customer-fields'=>'customer','job-fields'=>'job','quote-fields'=>'quote','invoice-fields'=>'invoice'];
            $data['entityType']=$entityMap[$tab];
            $data['fields']=$db->table('custom_field_defs')->where('company_id',$cid)->where('entity_type',$entityMap[$tab])->orderBy('sort_order')->get()->getResultArray();
        }

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

    public function saveJobType()
    {
        if (!$this->can('edit_global_settings')) return redirect()->back()->with('error','Access denied');
        $post=$this->request->getPost();
        if (!empty($post['id'])) model('JobTypeModel')->update((int)$post['id'],['name'=>trim($post['name']),'color'=>$post['color']??'#4f46e5','active'=>$post['active']??1]);
        else model('JobTypeModel')->insert(['company_id'=>$this->companyId,'name'=>trim($post['name']),'color'=>$post['color']??'#4f46e5','active'=>1,'sort_order'=>99]);
        return redirect()->to('/fieldly/public/index.php/global/job-types')->with('success','Job type saved.');
    }

    public function deleteJobType(int $id) { if (!$this->can('edit_global_settings')) return redirect()->back()->with('error','Access denied'); model('JobTypeModel')->delete($id); return redirect()->to('/fieldly/public/index.php/global/job-types')->with('success','Deleted.'); }

    public function saveStatus()
    {
        if (!$this->can('edit_global_settings')) return redirect()->back()->with('error','Access denied');
        $post=$this->request->getPost();
        $data=['name'=>trim($post['name']),'color'=>$post['color']??'#6b7280','is_complete'=>isset($post['is_complete'])?1:0,'is_cancelled'=>isset($post['is_cancelled'])?1:0,'triggers_invoice'=>isset($post['triggers_invoice'])?1:0,'active'=>$post['active']??1];
        if (!empty($post['id'])) model('JobStatusModel')->update((int)$post['id'],$data);
        else { $data['company_id']=$this->companyId; $data['is_default']=0; $data['sort_order']=99; model('JobStatusModel')->insert($data); }
        return redirect()->to('/fieldly/public/index.php/global/statuses')->with('success','Status saved.');
    }

    public function deleteStatus(int $id) { if (!$this->can('edit_global_settings')) return redirect()->back()->with('error','Access denied'); model('JobStatusModel')->delete($id); return redirect()->to('/fieldly/public/index.php/global/statuses')->with('success','Deleted.'); }

    public function savePricing()
    {
        if (!$this->can('edit_global_settings')) return redirect()->back()->with('error','Access denied');
        $post=$this->request->getPost();
        $data=['name'=>trim($post['name']),'basis'=>$post['basis']??'fixed_amount','chargeable'=>isset($post['chargeable'])?1:0,'description'=>trim($post['description']??''),'active'=>1];
        if (!empty($post['id'])) model('PricingTypeModel')->update((int)$post['id'],$data);
        else { $data['company_id']=$this->companyId; $data['is_default']=0; $data['sort_order']=99; model('PricingTypeModel')->insert($data); }
        return redirect()->to('/fieldly/public/index.php/global/pricing')->with('success','Pricing type saved.');
    }

    public function deletePricing(int $id) { if (!$this->can('edit_global_settings')) return redirect()->back()->with('error','Access denied'); model('PricingTypeModel')->delete($id); return redirect()->to('/fieldly/public/index.php/global/pricing')->with('success','Deleted.'); }

    public function saveTemplate()
    {
        if (!$this->can('edit_global_settings')) return redirect()->back()->with('error','Access denied');
        $post=$this->request->getPost(); $db=db_connect();
        if (!empty($post['id'])) {
            model('ChecklistTemplateModel')->update((int)$post['id'],['name'=>trim($post['name']),'job_type_id'=>$post['job_type_id']?:null]);
            if (!empty($post['items'])) { $db->table('checklist_template_items')->where('template_id',(int)$post['id'])->delete(); foreach ((array)$post['items'] as $i=>$text) if (trim($text)) $db->table('checklist_template_items')->insert(['template_id'=>(int)$post['id'],'text'=>trim($text),'sort_order'=>$i]); }
        } else {
            $id=model('ChecklistTemplateModel')->insert(['company_id'=>$this->companyId,'name'=>trim($post['name']),'job_type_id'=>$post['job_type_id']?:null,'created_at'=>date('Y-m-d H:i:s'),'updated_at'=>date('Y-m-d H:i:s')]);
            if (!empty($post['items'])) foreach ((array)$post['items'] as $i=>$text) if (trim($text)) $db->table('checklist_template_items')->insert(['template_id'=>$id,'text'=>trim($text),'sort_order'=>$i]);
        }
        return redirect()->to('/fieldly/public/index.php/global/templates')->with('success','Template saved.');
    }

    public function deleteTemplate(int $id) { if (!$this->can('edit_global_settings')) return redirect()->back()->with('error','Access denied'); model('ChecklistTemplateModel')->delete($id); db_connect()->table('checklist_template_items')->where('template_id',$id)->delete(); return redirect()->to('/fieldly/public/index.php/global/templates')->with('success','Deleted.'); }

    public function saveCustomField()
    {
        if (!$this->can('edit_global_settings')) return redirect()->back()->with('error','Access denied');
        $post=$this->request->getPost();
        $data=['name'=>trim($post['name']),'field_key'=>strtolower(preg_replace('/[^a-zA-Z0-9]/','_',$post['name'])),'field_type'=>$post['field_type']??'text','dropdown_options'=>$post['dropdown_options']??null,'required'=>isset($post['required'])?1:0,'active'=>1,'sort_order'=>99];
        if (!empty($post['id'])) model('CustomFieldDefModel')->update((int)$post['id'],$data);
        else { $data['company_id']=$this->companyId; $data['entity_type']=$post['entity_type']; model('CustomFieldDefModel')->insert($data); }
        return redirect()->back()->with('success','Custom field saved.');
    }

    public function deleteCustomField(int $id)
    {
        if (!$this->can('edit_global_settings')) return redirect()->back()->with('error','Access denied');
        model('CustomFieldDefModel')->delete($id);
        model('CustomFieldValueModel')->where('field_def_id',$id)->delete();
        return redirect()->back()->with('success','Deleted.');
    }
}
