<?php
namespace App\Controllers;

class AjaxController extends BaseController
{
    public function customerSearch()
    {
        $q=$this->request->getGet('q')??'';
        $db=db_connect();
        $customers=$db->table('customers c')
            ->select('c.id, c.ref, c.first_name, c.last_name, c.company_name, c.email, GROUP_CONCAT(cp.number SEPARATOR ", ") as phone')
            ->join('customer_phones cp','cp.customer_id=c.id AND cp.is_primary=1','left')
            ->where('c.company_id',$this->companyId)
            ->where('c.status','active')
            ->where('c.deleted_at IS NULL',null,false)
            ->groupStart()->like('c.first_name',$q)->orLike('c.last_name',$q)->orLike('c.company_name',$q)->orLike('c.ref',$q)->groupEnd()
            ->groupBy('c.id')
            ->limit(10)->get()->getResultArray();
        return $this->response->setJSON($customers);
    }

    public function jobSearch()
    {
        $q=$this->request->getGet('q')??'';
        $db=db_connect();
        $jobs=$db->table('jobs j')->select('j.id, j.number, j.title, 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',$this->companyId)->where('j.deleted_at IS NULL',null,false)->where('js.is_complete',0)->groupStart()->like('j.title',$q)->orLike('j.number',$q)->groupEnd()->limit(10)->get()->getResultArray();
        return $this->response->setJSON($jobs);
    }

    public function checkIn()
    {
        $jobId=(int)$this->request->getPost('job_id');
        $db=db_connect();
        $open=$db->table('check_ins')->where('company_id',$this->companyId)->where('user_id',$this->userId)->where('checked_out_at IS NULL',null,false)->get()->getRowArray();
        if ($open) return $this->response->setStatusCode(409)->setJSON(['success'=>false,'message'=>'Already checked in.']);
        $db->table('check_ins')->insert(['company_id'=>$this->companyId,'job_id'=>$jobId,'user_id'=>$this->userId,'checked_in_at'=>date('Y-m-d H:i:s'),'auto_time_entry'=>1]);
        return $this->response->setJSON(['success'=>true,'message'=>'Checked in.']);
    }

    public function checkOut()
    {
        $db=db_connect();
        $ci=$db->table('check_ins')->where('company_id',$this->companyId)->where('user_id',$this->userId)->where('checked_out_at IS NULL',null,false)->get()->getRowArray();
        if (!$ci) return $this->response->setStatusCode(404)->setJSON(['success'=>false,'message'=>'No active check-in.']);
        $mins=max(1,(int)round((time()-strtotime($ci['checked_in_at']))/60));
        $db->table('check_ins')->where('id',$ci['id'])->update(['checked_out_at'=>date('Y-m-d H:i:s'),'duration_mins'=>$mins]);
        if ($ci['auto_time_entry']) { $user=$db->table('users')->where('id',$this->userId)->get()->getRowArray(); model('TimeEntryModel')->insert(['company_id'=>$this->companyId,'job_id'=>$ci['job_id'],'check_in_id'=>$ci['id'],'user_id'=>$this->userId,'date'=>date('Y-m-d',strtotime($ci['checked_in_at'])),'duration_mins'=>$mins,'billable'=>1,'rate'=>$user['hourly_rate']??0,'notes'=>'Auto-logged from check-in','created_at'=>date('Y-m-d H:i:s')]); }
        return $this->response->setJSON(['success'=>true,'duration_mins'=>$mins]);
    }

    public function notifications()
    {
        $notifs=model('NotificationModel')->where('user_id',$this->userId)->where('company_id',$this->companyId)->orderBy('created_at','DESC')->findAll(20);
        $unread=model('NotificationModel')->where('user_id',$this->userId)->where('company_id',$this->companyId)->where('read_at IS NULL',null,false)->countAllResults();
        return $this->response->setJSON(['notifications'=>$notifs,'unread'=>$unread]);
    }

    public function markRead()
    {
        model('NotificationModel')->where('user_id',$this->userId)->where('company_id',$this->companyId)->where('read_at IS NULL',null,false)->set(['read_at'=>date('Y-m-d H:i:s')])->update();
        return $this->response->setJSON(['success'=>true]);
    }
}
