<?php
namespace App\Controllers;

class Assets extends BaseController
{
    public function index()
    {
        $filters = ['search'=>$this->request->getGet('search')??'','category'=>$this->request->getGet('category')??'','status'=>$this->request->getGet('status')??'','facility'=>$this->request->getGet('facility')??''];
        $q = $this->db->table('assets a')->select('a.*, f.name as facility_name')->join('facilities f','f.id=a.facility_id','left');
        $this->scopeFacilities($q, 'a.facility_id');
        if($filters['search']) $q->groupStart()->like('a.name',$filters['search'])->orLike('a.asset_code',$filters['search'])->groupEnd();
        if($filters['category']) $q->where('a.category',$filters['category']);
        if($filters['status']) $q->where('a.status',$filters['status']);
        if ($filters['facility']) {
            $q->where('a.facility_id', $filters['facility']);
        }
        $pg     = $this->paginate(25);
        $total  = (clone $q)->countAllResults(false);
        $assets = $q->orderBy('a.health_score', 'ASC')->limit($pg['perPage'], $pg['offset'])->get()->getResultArray();
        $facilities = $this->scopeFacilities($this->db->table('facilities')->where('status','active'))->get()->getResultArray();
        return view('assets/index', $this->viewData([
            'title'       => 'Assets',
            'assets'      => $assets,
            'filters'     => $filters,
            'facilities'  => $facilities,
            'totalCount'  => $total,
            'perPage'     => $pg['perPage'],
            'currentPage' => $pg['page'],
        ]));
    }

    public function create()
    {
        $facilities = $this->db->table('facilities')->where('status','active')->get()->getResultArray();
        return view('assets/create', $this->viewData(['title'=>'Add Asset','facilities'=>$facilities]));
    }

    public function store()
    {
        $rules = ['name'=>'required','facility_id'=>'required','category'=>'required'];
        if(!$this->validate($rules)) return redirect()->back()->withInput()->with('errors',$this->validator->getErrors());
        $code = strtoupper($this->request->getPost('asset_code')) ?: 'AST-'.date('Y').'-'.sprintf('%04d',rand(1,9999));
        $this->db->table('assets')->insert([
            'facility_id'=>$this->request->getPost('facility_id'),'name'=>esc($this->request->getPost('name')),
            'asset_code'=>$code,'category'=>$this->request->getPost('category'),'brand'=>esc($this->request->getPost('brand')),
            'model'=>esc($this->request->getPost('model')),'serial_number'=>esc($this->request->getPost('serial_number')),
            'location_in_facility'=>esc($this->request->getPost('location_in_facility')),
            'purchase_date'=>$this->request->getPost('purchase_date')?:null,'purchase_cost'=>$this->request->getPost('purchase_cost')?:null,
            'warranty_expiry'=>$this->request->getPost('warranty_expiry')?:null,'amc_expiry'=>$this->request->getPost('amc_expiry')?:null,
            'next_maintenance'=>$this->request->getPost('next_maintenance')?:null,'health_score'=>100,'status'=>'active',
            'notes'=>esc($this->request->getPost('notes')),
        ]);
        return redirect()->to(base_url('asset-register'))->with('success','Asset added.');
    }

    public function view(int $id)
    {
        $asset = $this->db->table('assets a')->select('a.*, f.name as facility_name')->join('facilities f','f.id=a.facility_id','left')->where('a.id',$id)->get()->getRowArray();
        if(!$asset) throw \CodeIgniter\Exceptions\PageNotFoundException::forPageNotFound();
        $workOrders = $this->db->table('work_orders')->where('asset_id',$id)->orderBy('created_at','DESC')->limit(10)->get()->getResultArray();
        return view('assets/view', $this->viewData(['title'=>$asset['name'],'asset'=>$asset,'workOrders'=>$workOrders]));
    }

    public function edit(int $id)
    {
        $asset = $this->db->table('assets')->where('id',$id)->get()->getRowArray();
        if(!$asset) throw \CodeIgniter\Exceptions\PageNotFoundException::forPageNotFound();
        $facilities = $this->db->table('facilities')->where('status','active')->get()->getResultArray();
        return view('assets/edit', $this->viewData(['title'=>'Edit Asset','asset'=>$asset,'facilities'=>$facilities]));
    }

    public function update(int $id)
    {
        $this->db->table('assets')->where('id',$id)->update([
            'name'=>esc($this->request->getPost('name')),'facility_id'=>$this->request->getPost('facility_id'),
            'category'=>$this->request->getPost('category'),'brand'=>esc($this->request->getPost('brand')),
            'model'=>esc($this->request->getPost('model')),'serial_number'=>esc($this->request->getPost('serial_number')),
            'location_in_facility'=>esc($this->request->getPost('location_in_facility')),
            'purchase_date'=>$this->request->getPost('purchase_date')?:null,'purchase_cost'=>$this->request->getPost('purchase_cost')?:null,
            'health_score'=>(int)$this->request->getPost('health_score'),'status'=>$this->request->getPost('status'),
            'warranty_expiry'=>$this->request->getPost('warranty_expiry')?:null,'amc_expiry'=>$this->request->getPost('amc_expiry')?:null,
            'next_maintenance'=>$this->request->getPost('next_maintenance')?:null,'notes'=>esc($this->request->getPost('notes')),
        ]);
        return redirect()->to(base_url('asset-register/view/'.$id))->with('success','Asset updated.');
    }

    public function delete(int $id)
    {
        $this->db->table('assets')->where('id',$id)->update(['status'=>'disposed']);
        return redirect()->to(base_url('asset-register'))->with('success','Asset marked as disposed.');
    }

    public function qrcode(int $id)
    {
        $asset = $this->db->table('assets')->where('id',$id)->get()->getRowArray();
        if (!$asset) throw \CodeIgniter\Exceptions\PageNotFoundException::forPageNotFound();
        // Generate QR data URL using Google Charts API (no lib needed)
        $qrData = urlencode(base_url('asset-register/view/'.$id).'|'.$asset['asset_code'].'|'.$asset['name']);
        $qrUrl  = "https://chart.googleapis.com/chart?chs=200x200&cht=qr&chl={$qrData}&choe=UTF-8";
        return view('assets/qrcode', $this->viewData(['title'=>'QR Code — '.$asset['asset_code'],'asset'=>$asset,'qrUrl'=>$qrUrl]));
    }

    public function history(int $id)
    {
        $asset = $this->db->table('assets')->where('id',$id)->get()->getRowArray();
        $history = $this->db->table('work_orders w')
            ->select('w.*, u.name as technician_name')
            ->join('users u','u.id=w.assigned_to','left')
            ->where('w.asset_id',$id)
            ->orderBy('w.created_at','DESC')
            ->get()->getResultArray();

        // Depreciation — straight line: (cost - 0) / 10 years
        $depreciationPerYear = $asset['purchase_cost'] ? $asset['purchase_cost'] / 10 : 0;
        $yearsOwned = $asset['purchase_date'] ? (time() - strtotime($asset['purchase_date'])) / (365*24*3600) : 0;
        $currentValue = max(0, $asset['purchase_cost'] - ($depreciationPerYear * $yearsOwned));

        return view('assets/history', $this->viewData([
            'title'              => 'Asset History — '.$asset['asset_code'],
            'asset'              => $asset,
            'history'            => $history,
            'depreciationPerYear'=> $depreciationPerYear,
            'currentValue'       => $currentValue,
            'yearsOwned'         => round($yearsOwned,1),
        ]));
    }
}
