<?php
namespace App\Controllers;

class CalendarController extends BaseController
{
    public function index()
    {
        if (!$this->can('view_calendar')) return redirect()->to('/')->with('error','Access denied');
        $db=$db=db_connect(); $cid=$this->companyId;
        $from=$this->request->getGet('from')??date('Y-m-01');
        $to=$this->request->getGet('to')??date('Y-m-t');

        $visits=$db->table('visits v')
            ->select('v.*, j.number as job_number, j.title as job_title, c.first_name, c.last_name, c.company_name')
            ->join('jobs j','j.id=v.job_id')
            ->join('customers c','c.id=j.customer_id')
            ->where('v.company_id',$cid)
            ->where('v.scheduled_start >=', $from.' 00:00:00')
            ->where('v.scheduled_start <=', $to.' 23:59:59')
            ->orderBy('v.scheduled_start','ASC')
            ->get()->getResultArray();

        $jobs=$db->table('jobs j')->select('j.id, j.number, j.title, j.scheduled_date, j.scheduled_time, js.name as status_name, js.color as status_color, c.first_name, c.last_name, c.company_name')->join('customers c','c.id=j.customer_id')->join('job_statuses js','js.id=j.status_id')->where('j.company_id',$cid)->where('j.deleted_at IS NULL',null,false)->where('j.scheduled_date IS NOT NULL',null,false)->where('j.scheduled_date >=',$from)->where('j.scheduled_date <=',$to)->get()->getResultArray();

        $allJobs=$db->table('jobs j')->select('j.id, j.number, j.title')->join('job_statuses js','js.id=j.status_id')->where('j.company_id',$cid)->where('j.deleted_at IS NULL',null,false)->where('js.is_complete',0)->orderBy('j.created_at','DESC')->get()->getResultArray();
        $users=$db->table('users')->where('company_id',$cid)->where('status','active')->where('deleted_at IS NULL',null,false)->get()->getResultArray();

        return $this->view('calendar/index', compact('visits','jobs','allJobs','users','from','to'));
    }

    public function createVisit()
    {
        if (!$this->can('edit_calendar')) return redirect()->back()->with('error','Access denied');
        $post=$this->request->getPost();
        if (!$this->validate(['job_id'=>'required|integer','scheduled_start'=>'required'])) return redirect()->back()->withInput()->with('errors',$this->validator->getErrors());
        $db=db_connect();
        $id=$db->table('visits')->insert(['company_id'=>$this->companyId,'job_id'=>(int)$post['job_id'],'title'=>trim($post['title']??''),'status'=>'scheduled','scheduled_start'=>$post['scheduled_start'],'scheduled_end'=>$post['scheduled_end']??null,'notes'=>trim($post['notes']??''),'created_by'=>$this->userId,'created_at'=>date('Y-m-d H:i:s'),'updated_at'=>date('Y-m-d H:i:s')]);
        if (!empty($post['assignees'])) foreach ((array)$post['assignees'] as $uid) $db->table('visit_assignees')->insert(['visit_id'=>$db->insertID(),'user_id'=>(int)$uid]);
        return redirect()->to('/fieldly/public/index.php/calendar')->with('success','Visit scheduled.');
    }

    public function updateVisit(int $id)
    {
        if (!$this->can('edit_calendar')) return redirect()->back()->with('error','Access denied');
        $post=$this->request->getPost();
        db_connect()->table('visits')->where('id',$id)->where('company_id',$this->companyId)->update(['title'=>trim($post['title']??''),'status'=>$post['status']??'scheduled','scheduled_start'=>$post['scheduled_start'],'scheduled_end'=>$post['scheduled_end']??null,'notes'=>trim($post['notes']??''),'updated_at'=>date('Y-m-d H:i:s')]);
        return redirect()->to('/fieldly/public/index.php/calendar')->with('success','Visit updated.');
    }

    public function deleteVisit(int $id)
    {
        if (!$this->can('edit_calendar')) return redirect()->back()->with('error','Access denied');
        db_connect()->table('visits')->where('id',$id)->where('company_id',$this->companyId)->delete();
        return redirect()->to('/fieldly/public/index.php/calendar')->with('success','Visit deleted.');
    }
}
