<?php

namespace App\Controllers;

class Partner extends BaseController
{
    private function partner(): ?array { return db_connect()->table('partners')->where('user_id',auth_id())->get()->getRowArray(); }
    public function dashboard()
    {
        $p=$this->partner(); $stats=['labs'=>0,'orders'=>0,'referrals'=>0];
        if($p){$db=db_connect();$stats['labs']=$db->table('lab_requests')->where('partner_id',$p['id'])->whereNotIn('status',['completed','cancelled'])->countAllResults();$stats['orders']=$db->table('pharmacy_orders')->where('partner_id',$p['id'])->whereNotIn('status',['delivered','cancelled'])->countAllResults();$stats['referrals']=$db->table('partner_referrals')->where('partner_id',$p['id'])->whereNotIn('status',['completed','cancelled'])->countAllResults();}
        return $this->portal('partner/dashboard',['title'=>'Partner Dashboard','partner'=>$p,'stats'=>$stats],'partner');
    }
    public function labs(){return $this->generic('Lab Requests','Manage samples, processing status and result release.','lab_requests');}
    public function pharmacy(){return $this->generic('Pharmacy Orders','Manage prescription fulfilment and home delivery.','pharmacy_orders');}
    public function referrals(){return $this->generic('Referrals','Coordinate patient referrals from TibaLeta practitioners.','partner_referrals');}
    public function payments(){return $this->portal('portal/page',['title'=>'Payments','heading'=>'Payments','intro'=>'Partner settlement data will appear here when a payment provider/settlement account is connected.','rows'=>[]],'partner');}
    public function settings(){return $this->portal('portal/page',['title'=>'Partner Settings','heading'=>'Partner Settings','intro'=>'Manage locations, contacts and integration configuration.','rows'=>$this->partner()?[$this->partner()]:[]],'partner');}
    private function generic(string $title,string $intro,string $table,bool $partnerScoped=true){$rows=[];$p=$this->partner();if($p){try{$b=db_connect()->table($table);if($partnerScoped)$b->where('partner_id',$p['id']);$rows=$b->orderBy('id','DESC')->limit(100)->get()->getResultArray();}catch(\Throwable $e){}}return $this->portal('portal/page',['title'=>$title,'heading'=>$title,'intro'=>$intro,'rows'=>$rows],'partner');}
}
