<?php
namespace App\Controllers;

class TimeController extends BaseController
{
    public function index()
    {
        if (!$this->can('view_time')) return redirect()->to('/')->with('error','Access denied');
        $db=$db=db_connect(); $cid=$this->companyId;
        $userId=$this->can('edit_time')?($this->request->getGet('user_id')??(null)):$this->userId;
        $dateFrom=$this->request->getGet('date_from')??date('Y-m-01');
        $dateTo=$this->request->getGet('date_to')??date('Y-m-t');
        $jobId=$this->request->getGet('job_id');

        $b=$db->table('time_entries te')->select('te.*, u.first_name, u.last_name, j.number as job_number, j.title as job_title')->join('users u','u.id=te.user_id')->join('jobs j','j.id=te.job_id','left')->where('te.company_id',$cid)->where('te.deleted_at IS NULL',null,false);
        if ($userId) $b->where('te.user_id',$userId);
        if ($dateFrom) $b->where('te.date >=',$dateFrom);
        if ($dateTo)   $b->where('te.date <=',$dateTo);
        if ($jobId)    $b->where('te.job_id',$jobId);
        $entries=$b->orderBy('te.date','DESC')->orderBy('te.start_time','DESC')->get()->getResultArray();

        $totalMins=array_sum(array_column($entries,'duration_mins'));
        $billableMins=array_sum(array_map(fn($t)=>$t['billable']?$t['duration_mins']:0,$entries));

        $users=$db->table('users')->where('company_id',$cid)->where('status','active')->where('deleted_at IS NULL',null,false)->get()->getResultArray();
        $jobs=$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)->orderBy('j.created_at','DESC')->limit(100)->get()->getResultArray();

        return $this->view('time/index', compact('entries','totalMins','billableMins','users','jobs','userId','dateFrom','dateTo','jobId'));
    }

    public function log()
    {
        if (!$this->can('log_time')) return redirect()->back()->with('error','Access denied');
        $post=$this->request->getPost();
        if (!$this->validate(['job_id'=>'required|integer','date'=>'required','duration_mins'=>'required|integer'])) return redirect()->back()->withInput()->with('errors',$this->validator->getErrors());
        $user=db_connect()->table('users')->where('id',$this->userId)->get()->getRowArray();
        model('TimeEntryModel')->insert(['company_id'=>$this->companyId,'job_id'=>(int)$post['job_id'],'user_id'=>$this->userId,'date'=>$post['date'],'start_time'=>$post['start_time']?:null,'end_time'=>$post['end_time']?:null,'duration_mins'=>(int)$post['duration_mins'],'billable'=>isset($post['billable'])?1:0,'rate'=>$post['rate']??($user['hourly_rate']??0),'notes'=>trim($post['notes']??''),'created_at'=>date('Y-m-d H:i:s')]);
        return redirect()->to('/fieldly/public/index.php/time')->with('success','Time logged.');
    }

    public function update(int $id)
    {
        if (!$this->can('edit_time')) return redirect()->back()->with('error','Access denied');
        $post=$this->request->getPost();
        model('TimeEntryModel')->update($id,['date'=>$post['date'],'duration_mins'=>(int)$post['duration_mins'],'billable'=>isset($post['billable'])?1:0,'rate'=>$post['rate']??0,'notes'=>trim($post['notes']??'')]);
        return redirect()->back()->with('success','Entry updated.');
    }

    public function delete(int $id)
    {
        if (!$this->can('edit_time')) return redirect()->back()->with('error','Access denied');
        model('TimeEntryModel')->update($id,['deleted_at'=>date('Y-m-d H:i:s')]);
        return redirect()->back()->with('success','Entry deleted.');
    }
}
