<?php

namespace App\Controllers;

use App\Services\AuditService;

class Admin extends BaseController
{
    public function dashboard()
    {
        $db=db_connect();
        $stats=['active'=>$db->table('care_requests')->whereIn('status',['accepted','en_route','arrived','in_progress'])->countAllResults(),'available'=>$db->table('practitioner_profiles')->where(['verification_status'=>'verified','is_online'=>1])->countAllResults(),'enroute'=>$db->table('care_requests')->where('status','en_route')->countAllResults(),'waiting'=>$db->table('care_requests')->whereIn('status',['requested','matching','offered'])->countAllResults(),'unassigned'=>$db->table('care_requests')->where('assigned_practitioner_id',null)->whereNotIn('status',['completed','cancelled'])->countAllResults(),'escalated'=>$db->table('care_requests')->where('status','escalated')->countAllResults()];
        $activity=$db->table('audit_logs')->orderBy('id','DESC')->limit(8)->get()->getResultArray();
        $requests=$db->table('care_requests cr')->select('cr.*,s.name service_name')->join('services s','s.id=cr.service_id')->orderBy('cr.id','DESC')->limit(10)->get()->getResultArray();
        return $this->portal('admin/dashboard',['title'=>'Operations Command Centre','stats'=>$stats,'activity'=>$activity,'requests'=>$requests],'admin');
    }

    public function practitioners(){ $rows=db_connect()->table('practitioner_profiles pp')->select('pp.*,u.full_name,u.email,u.phone')->join('users u','u.id=pp.user_id')->orderBy('pp.id','DESC')->get()->getResultArray(); return $this->portal('admin/practitioners',['title'=>'Practitioners','rows'=>$rows],'admin'); }
    public function credentials(){ $rows=db_connect()->table('practitioner_credentials c')->select('c.*,pp.profession,u.full_name practitioner_name')->join('practitioner_profiles pp','pp.id=c.practitioner_id')->join('users u','u.id=pp.user_id')->orderBy('c.id','DESC')->get()->getResultArray(); return $this->portal('admin/credentials',['title'=>'Credential Review','rows'=>$rows],'admin'); }
    public function credentialDecision(int $id,string $decision){if(!in_array($decision,['verified','rejected'],true))return redirect()->back();$row=db_connect()->table('practitioner_credentials')->where('id',$id)->get()->getRowArray();if(!$row)return redirect()->back()->with('error','Credential not found.');db_connect()->table('practitioner_credentials')->where('id',$id)->update(['status'=>$decision,'verified_at'=>$decision==='verified'?date('Y-m-d H:i:s'):null,'verified_by'=>auth_id(),'updated_at'=>date('Y-m-d H:i:s')]);(new AuditService())->log('credential.'.$decision,'credential',$id);return redirect()->back()->with('success','Credential review saved.'); }

    public function patients(){ return $this->generic('Patients','Manage patient accounts while respecting clinical access boundaries.','patient_profiles'); }
    public function requests(){ return $this->generic('Care Requests','Monitor dispatch, assignment, cancellations and escalations.','care_requests'); }
    public function visits(){ return $this->generic('Visits','Operational visibility into active and completed care visits.','visits'); }
    public function clinical(){ $rows=db_connect()->table('clinical_notes')->select('id,visit_id,patient_id,practitioner_id,is_locked,locked_at,created_at,updated_at')->orderBy('id','DESC')->limit(100)->get()->getResultArray(); return $this->portal('portal/page',['title'=>'Clinical Oversight','heading'=>'Clinical Oversight','intro'=>'Restricted governance metadata only; clinical narrative content is not exposed in the operations dashboard.','rows'=>$rows],'admin'); }
    public function payments(){ return $this->generic('Payments','Transactions, refunds, receipts and reconciliation.','payments'); }
    public function payouts(){ return $this->generic('Practitioner Payouts','Earnings, fees, settlement status and payout references.','payouts'); }
    public function partners(){ return $this->generic('Partners','Labs, pharmacies, hospitals, insurers and integration status.','partners'); }
    public function reviews(){ return $this->generic('Reviews & Complaints','Moderate feedback and coordinate service recovery.','reviews'); }
    public function services(){ $rows=db_connect()->table('services')->orderBy('sort_order')->get()->getResultArray(); return $this->portal('admin/services',['title'=>'Services & Pricing','rows'=>$rows],'admin'); }
    public function saveService(){ $rules=['name'=>'required|max_length[120]','slug'=>'required|alpha_dash|max_length[140]','base_price'=>'required|decimal|greater_than_equal_to[0]','duration_minutes'=>'required|integer|greater_than[0]','sort_order'=>'permit_empty|integer'];if(!$this->validate($rules))return redirect()->back()->withInput()->with('errors',$this->validator->getErrors());$id=(int)$this->request->getPost('id');$data=['name'=>trim((string)$this->request->getPost('name')),'slug'=>trim((string)$this->request->getPost('slug')),'description'=>trim((string)$this->request->getPost('description')),'base_price'=>(float)$this->request->getPost('base_price'),'duration_minutes'=>(int)$this->request->getPost('duration_minutes'),'sort_order'=>(int)$this->request->getPost('sort_order'),'is_active'=>1,'updated_at'=>date('Y-m-d H:i:s')];$db=db_connect();if($id){$db->table('services')->where('id',$id)->update($data);}else{$data['created_at']=date('Y-m-d H:i:s');$db->table('services')->insert($data);$id=(int)$db->insertID();}(new AuditService())->log('service.saved','service',$id);return redirect()->back()->with('success','Service saved.'); }
    public function toggleService(int $id){$row=db_connect()->table('services')->where('id',$id)->get()->getRowArray();if(!$row)return redirect()->back();db_connect()->table('services')->where('id',$id)->update(['is_active'=>$row['is_active']?0:1,'updated_at'=>date('Y-m-d H:i:s')]);(new AuditService())->log('service.toggled','service',$id,['active'=>!$row['is_active']]);return redirect()->back()->with('success','Service availability updated.'); }
    public function analytics(){ $snapshot=(new \App\Services\AnalyticsService())->operationsSnapshot(); return $this->portal('admin/analytics',['title'=>'Analytics','snapshot'=>$snapshot],'admin'); }
    public function audit(){ return $this->generic('Audit Logs','Immutable accountability trail for sensitive platform actions.','audit_logs'); }
    public function settings(){ return $this->portal('portal/page',['title'=>'Platform Settings','heading'=>'Platform Settings','intro'=>'Configure coverage zones, dispatch rules, notification channels, integrations and operational defaults.','rows'=>[]],'admin'); }

    public function approvePractitioner(int $id)
    {
        db_connect()->table('practitioner_profiles')->where('id',$id)->update(['verification_status'=>'verified','verified_at'=>date('Y-m-d H:i:s'),'verified_by'=>auth_id(),'updated_at'=>date('Y-m-d H:i:s')]);
        (new AuditService())->log('practitioner.verified','practitioner',$id);
        return redirect()->back()->with('success','Practitioner verified and eligible for dispatch.');
    }

    private function generic(string $title,string $intro,string $table)
    {
        $rows=[]; try{$rows=db_connect()->table($table)->orderBy('id','DESC')->limit(100)->get()->getResultArray();}catch(\Throwable $e){}
        return $this->portal('portal/page',['title'=>$title,'heading'=>$title,'intro'=>$intro,'rows'=>$rows],'admin');
    }
}
