<?php
namespace App\Controllers;

class Estimations extends BaseController
{
    public function index()
    {
        $pg          = $this->paginate(20);
        $currentPage = $pg['page'];
        $perPage     = $pg['perPage'];
        $offset      = $pg['offset'];

        $q = $this->db->table('estimations e')
            ->select('e.*, f.name as facility_name, u.name as created_by_name')
            ->join('facilities f','f.id=e.facility_id','left')
            ->join('users u','u.id=e.created_by','left');

        $status = $this->request->getGet('status') ?? '';
        if ($status) $q->where('e.status',$status);
        $total = (clone $q)->countAllResults(false);
        $ests  = $q->orderBy('e.created_at','DESC')->limit($perPage,$offset)->get()->getResultArray();

        $kpi = [
            'draft'    => $this->db->table('estimations')->where('status','draft')->countAllResults(),
            'pending'  => $this->db->table('estimations')->where('status','pending_approval')->countAllResults(),
            'approved' => $this->db->table('estimations')->where('status','approved')->countAllResults(),
            'converted'=> $this->db->table('estimations')->where('status','converted')->countAllResults(),
        ];

        return view('estimations/index', $this->viewData([
            'title'=>'Estimations','ests'=>$ests,'kpi'=>$kpi,
            'totalCount'=>$total,'perPage'=>$perPage,'currentPage'=>$currentPage,'filterStatus'=>$status,
        ]));
    }

    public function create()
    {
        $facilities = $this->db->table('facilities')->where('status','active')->get()->getResultArray();
        $workOrders = $this->db->table('work_orders')->whereIn('status',['new','assigned','in_progress'])->orderBy('created_at','DESC')->limit(50)->get()->getResultArray();
        $vatEnabled = ($this->settings['vat_enabled']??'0')==='1';
        $vatRate    = (float)($this->settings['vat_rate']??5);
        return view('estimations/create', $this->viewData([
            'title'=>'New Estimation','facilities'=>$facilities,'workOrders'=>$workOrders,
            'vatEnabled'=>$vatEnabled,'vatRate'=>$vatRate,
        ]));
    }

    public function store()
    {
        $rules = ['facility_id'=>'required|integer','title'=>'required|max_length[255]'];
        if (!$this->validate($rules)) return redirect()->back()->withInput()->with('errors',$this->validator->getErrors());

        $laborCost    = (float)($this->request->getPost('labor_cost')    ?? 0);
        $materialCost = (float)($this->request->getPost('material_cost') ?? 0);
        $otherCost    = (float)($this->request->getPost('other_cost')    ?? 0);
        $subtotal     = $laborCost + $materialCost + $otherCost;
        $vatEnabled   = ($this->settings['vat_enabled']??'0')==='1';
        $vatRate      = $vatEnabled ? (float)($this->settings['vat_rate']??5) : 0;
        $vatAmt       = round($subtotal * $vatRate / 100, 2);
        $total        = $subtotal + $vatAmt;
        $estNum       = $this->generateNumber('EST','estimations','est_number');

        $this->db->table('estimations')->insert([
            'est_number'    => $estNum,
            'facility_id'   => (int)$this->request->getPost('facility_id'),
            'wo_id'         => $this->request->getPost('wo_id') ?: null,
            'title'         => esc($this->request->getPost('title')),
            'description'   => esc($this->request->getPost('description')??''),
            'labor_cost'    => $laborCost,
            'material_cost' => $materialCost,
            'other_cost'    => $otherCost,
            'subtotal'      => $subtotal,
            'vat_rate'      => $vatRate,
            'vat_amount'    => $vatAmt,
            'total'         => $total,
            'status'        => 'draft',
            'notes'         => esc($this->request->getPost('notes')??''),
            'created_by'    => session()->get('user_id'),
        ]);
        $estId = $this->db->insertID();

        // Save line items
        $descs  = $this->request->getPost('item_desc')  ?? [];
        $types  = $this->request->getPost('item_type')  ?? [];
        $qtys   = $this->request->getPost('item_qty')   ?? [];
        $costs  = $this->request->getPost('item_cost')  ?? [];
        foreach ($descs as $i => $desc) {
            if (empty($desc)) continue;
            $q = (float)($qtys[$i]??1);
            $c = (float)($costs[$i]??0);
            $this->db->table('estimation_items')->insert([
                'est_id'=>$estId,'type'=>$types[$i]??'material',
                'description'=>esc($desc),'quantity'=>$q,'unit_cost'=>$c,'total_cost'=>$q*$c,
            ]);
        }

        $this->logActivity('create','estimations',$estId,"Created $estNum");
        return redirect()->to(base_url('estimations/view/'.$estId))->with('success',"Estimation $estNum created.");
    }

    public function view(int $id)
    {
        $est = $this->db->table('estimations e')
            ->select('e.*, f.name as facility_name, u.name as created_by_name, ap.name as approved_by_name, wo.wo_number')
            ->join('facilities f','f.id=e.facility_id','left')
            ->join('users u','u.id=e.created_by','left')
            ->join('users ap','ap.id=e.approved_by','left')
            ->join('work_orders wo','wo.id=e.wo_id','left')
            ->where('e.id',$id)->get()->getRowArray();
        if (!$est) throw \CodeIgniter\Exceptions\PageNotFoundException::forPageNotFound();

        $items = $this->db->table('estimation_items')->where('est_id',$id)->get()->getResultArray();
        return view('estimations/view', $this->viewData([
            'title'=>$est['est_number'],'est'=>$est,'items'=>$items,
        ]));
    }

    public function edit(int $id)
    {
        $est = $this->db->table('estimations')->where('id',$id)->get()->getRowArray();
        if (!$est || in_array($est['status'],['approved','converted'])) return redirect()->back()->with('error','Cannot edit this estimation.');
        $items      = $this->db->table('estimation_items')->where('est_id',$id)->get()->getResultArray();
        $facilities = $this->db->table('facilities')->where('status','active')->get()->getResultArray();
        $workOrders = $this->db->table('work_orders')->whereIn('status',['new','assigned','in_progress'])->get()->getResultArray();
        $vatEnabled = ($this->settings['vat_enabled']??'0')==='1';
        $vatRate    = (float)($this->settings['vat_rate']??5);
        return view('estimations/edit', $this->viewData([
            'title'=>'Edit '.$est['est_number'],'est'=>$est,'items'=>$items,
            'facilities'=>$facilities,'workOrders'=>$workOrders,'vatEnabled'=>$vatEnabled,'vatRate'=>$vatRate,
        ]));
    }

    public function update(int $id)
    {
        $est = $this->db->table('estimations')->where('id',$id)->get()->getRowArray();
        if (!$est) throw \CodeIgniter\Exceptions\PageNotFoundException::forPageNotFound();

        $laborCost    = (float)($this->request->getPost('labor_cost')    ?? 0);
        $materialCost = (float)($this->request->getPost('material_cost') ?? 0);
        $otherCost    = (float)($this->request->getPost('other_cost')    ?? 0);
        $subtotal     = $laborCost + $materialCost + $otherCost;
        $vatEnabled   = ($this->settings['vat_enabled']??'0')==='1';
        $vatRate      = $vatEnabled ? (float)($this->settings['vat_rate']??5) : 0;
        $vatAmt       = round($subtotal * $vatRate / 100, 2);

        $this->db->table('estimations')->where('id',$id)->update([
            'facility_id'   => (int)$this->request->getPost('facility_id'),
            'wo_id'         => $this->request->getPost('wo_id') ?: null,
            'title'         => esc($this->request->getPost('title')),
            'description'   => esc($this->request->getPost('description')??''),
            'labor_cost'    => $laborCost,
            'material_cost' => $materialCost,
            'other_cost'    => $otherCost,
            'subtotal'      => $subtotal,
            'vat_rate'      => $vatRate,
            'vat_amount'    => $vatAmt,
            'total'         => $subtotal + $vatAmt,
            'revision'      => $est['revision'] + 1,
            'notes'         => esc($this->request->getPost('notes')??''),
        ]);

        $this->db->table('estimation_items')->where('est_id',$id)->delete();
        $descs = $this->request->getPost('item_desc') ?? [];
        $types = $this->request->getPost('item_type') ?? [];
        $qtys  = $this->request->getPost('item_qty')  ?? [];
        $costs = $this->request->getPost('item_cost') ?? [];
        foreach ($descs as $i => $desc) {
            if (empty($desc)) continue;
            $q = (float)($qtys[$i]??1); $c = (float)($costs[$i]??0);
            $this->db->table('estimation_items')->insert(['est_id'=>$id,'type'=>$types[$i]??'material','description'=>esc($desc),'quantity'=>$q,'unit_cost'=>$c,'total_cost'=>$q*$c]);
        }

        $this->logActivity('update','estimations',$id);
        return redirect()->to(base_url('estimations/view/'.$id))->with('success','Estimation updated.');
    }

    public function approve(int $id)
    {
        $this->requireRole('super_admin','facility_manager','finance_manager');
        $this->db->table('estimations')->where('id',$id)->update([
            'status'=>'approved','approved_by'=>session()->get('user_id'),'approved_at'=>date('Y-m-d H:i:s'),
        ]);
        $this->logActivity('approve','estimations',$id);
        return redirect()->to(base_url('estimations/view/'.$id))->with('success','Estimation approved.');
    }

    public function convertToWorkOrder(int $id)
    {
        $this->requireRole('super_admin','facility_manager');
        $est = $this->db->table('estimations')->where('id',$id)->get()->getRowArray();
        if (!$est || $est['status']!=='approved') return redirect()->back()->with('error','Only approved estimations can be converted.');

        $woNum = $this->generateNumber('WO','work_orders','wo_number');
        $this->db->table('work_orders')->insert([
            'wo_number'      => $woNum,
            'facility_id'    => $est['facility_id'],
            'title'          => $est['title'],
            'description'    => $est['description'],
            'type'           => 'corrective',
            'priority'       => 'medium',
            'status'         => 'new',
            'estimated_cost' => $est['total'],
            'approval_status'=> 'approved',
            'created_by'     => session()->get('user_id'),
        ]);
        $woId = $this->db->insertID();
        $this->db->table('estimations')->where('id',$id)->update(['status'=>'converted','wo_id'=>$woId]);
        $this->logActivity('convert','estimations',$id,"Converted to WO $woNum");
        return redirect()->to(base_url('workorders/view/'.$woId))->with('success',"Estimation converted to Work Order $woNum.");
    }

    public function printView(int $id)
    {
        $est   = $this->db->table('estimations e')->select('e.*, f.name as facility_name, u.name as created_by_name')->join('facilities f','f.id=e.facility_id','left')->join('users u','u.id=e.created_by','left')->where('e.id',$id)->get()->getRowArray();
        if (!$est) throw \CodeIgniter\Exceptions\PageNotFoundException::forPageNotFound();
        $items = $this->db->table('estimation_items')->where('est_id',$id)->get()->getResultArray();
        return view('estimations/print', $this->viewData(['title'=>'Print: '.$est['est_number'],'est'=>$est,'items'=>$items,'usePdf'=>true]));
    }
}
