<?php

class BorderCrossingController extends Controller
{
    private BorderCrossing $borders; private Document $documents;
    public function __construct(){ $this->borders=new BorderCrossing();$this->documents=new Document(); }
    private function manage():void{Auth::requireLogin();if(!can('border.manage')&&!can('driver.border')){http_response_code(403);require app_path('Views/errors/403.php');exit;}}
    public function index():void{$this->manage();$search=trim($_GET['search']??'');$crossings=current_role()==='driver'?$this->borders->forDriver((int)(Auth::user()['driver_id']??0)):$this->borders->all($search?:null);$this->view('borders/index',compact('crossings','search'));}
    public function create():void{Auth::requireLogin();if(!can('border.manage')){http_response_code(403);require app_path('Views/errors/403.php');exit;}$db=Database::connection();$loads=$db->query("SELECT id,load_number FROM loads WHERE status NOT IN ('paid','cancelled') ORDER BY id DESC")->fetchAll();$brokers=$this->borders->customsBrokers();$statuses=BorderCrossing::STATUSES;$record=null;$this->view('borders/form',compact('loads','brokers','statuses','record'));}
    public function store():void{Auth::requireLogin();if(!can('border.manage')){http_response_code(403);exit;}Csrf::verify();if(empty($_POST['load_id'])||empty(trim($_POST['crossing_name']??''))){$this->flash('danger','Load and crossing name are required.');$this->redirect('/borders/create');}$id=$this->borders->create($_POST);log_activity('border_crossing_created','Created border crossing #'.$id);$this->flash('success','Border crossing created.');$this->redirect('/borders/show?id='.$id);}
    public function edit():void{Auth::requireLogin();if(!can('border.manage')){http_response_code(403);require app_path('Views/errors/403.php');exit;}$record=$this->borders->find((int)($_GET['id']??0));if(!$record){$this->redirect('/borders');}$db=Database::connection();$loads=$db->query('SELECT id,load_number FROM loads ORDER BY id DESC')->fetchAll();$brokers=$this->borders->customsBrokers();$statuses=BorderCrossing::STATUSES;$this->view('borders/form',compact('loads','brokers','statuses','record'));}
    public function update():void{Auth::requireLogin();if(!can('border.manage')){http_response_code(403);exit;}Csrf::verify();$id=(int)($_POST['id']??0);$this->borders->update($id,$_POST);$this->flash('success','Border crossing updated.');$this->redirect('/borders/show?id='.$id);}
    public function show():void{$this->manage();$record=$this->authorized((int)($_GET['id']??0));$documents=$this->documents->forRelation('border_crossing',(int)$record['id']);$this->view('borders/show',compact('record','documents'));}
    public function status():void{$this->manage();Csrf::verify();$record=$this->authorized((int)($_POST['id']??0));$status=$_POST['status']??'not_started';$this->borders->setStatus((int)$record['id'],$status);notify_roles(['owner','admin','dispatcher'],'Border status updated',$record['crossing_number'].' is now '.readable_status($status).'.','/borders/show?id='.(int)$record['id'],in_array($status,['on_hold','rejected_returned'],true)?'danger':'info');log_activity('border_status_updated',$record['crossing_number'].' → '.readable_status($status));$this->flash('success','Crossing status updated.');$this->redirect('/borders/show?id='.$record['id']);}
    public function checklist():void{Auth::requireLogin();if(!can('border.manage')){http_response_code(403);exit;}Csrf::verify();$record=$this->authorized((int)($_POST['crossing_id']??0));$this->borders->updateChecklist((int)($_POST['item_id']??0),$_POST['status']??'missing',null,trim((string)($_POST['notes']??''))?:null);$this->flash('success','Checklist item updated.');$this->redirect('/borders/show?id='.$record['id']);}
    public function issue():void{$this->manage();Csrf::verify();$record=$this->authorized((int)($_POST['crossing_id']??0));$this->borders->addIssue((int)$record['id'],$_POST);notify_roles(['owner','admin','dispatcher'],'Border issue reported',$record['crossing_number'].' — '.trim((string)($_POST['issue_type']??'Issue')).'.','/borders/show?id='.(int)$record['id'],'danger');$this->flash('success','Border issue recorded.');$this->redirect('/borders/show?id='.$record['id']);}
    public function upload():void{$this->manage();Csrf::verify();$record=$this->authorized((int)($_POST['crossing_id']??0));if(empty($_FILES['file']['tmp_name'])||($_FILES['file']['error']??UPLOAD_ERR_NO_FILE)!==UPLOAD_ERR_OK){$this->flash('danger','Select a file.');$this->redirect('/borders/show?id='.$record['id']);}$f=$_FILES['file'];$original=basename($f['name']);$ext=strtolower(pathinfo($original,PATHINFO_EXTENSION));if(!in_array($ext,['pdf','jpg','jpeg','png','webp','heic'],true)){$this->flash('danger','Only images and PDF files are allowed.');$this->redirect('/borders/show?id='.$record['id']);}$folder=storage_path('uploads/borders/'.date('Y/m'));if(!is_dir($folder))mkdir($folder,0755,true);$stored=bin2hex(random_bytes(16)).'.'.$ext;$target=$folder.DIRECTORY_SEPARATOR.$stored;if(!move_uploaded_file($f['tmp_name'],$target)){$this->flash('danger','Upload failed.');$this->redirect('/borders/show?id='.$record['id']);}$docId=$this->documents->create(['related_type'=>'border_crossing','related_id'=>(int)$record['id'],'document_type'=>trim((string)($_POST['document_type']??'Border Document')),'file_name'=>$original,'stored_name'=>$stored,'file_path'=>str_replace(base_path().DIRECTORY_SEPARATOR,'',$target),'mime_type'=>$f['type']??null,'file_size'=>$f['size']??null,'expires_at'=>null,'notes'=>$_POST['notes']??null,'latitude'=>$_POST['latitude']??null,'longitude'=>$_POST['longitude']??null,'location_address'=>$_POST['location_address']??null]);if(!empty($_POST['checklist_item_id']))$this->borders->updateChecklist((int)$_POST['checklist_item_id'],'uploaded',$docId);$this->flash('success','Border file uploaded.');$this->redirect('/borders/show?id='.$record['id']);}
    public function brokerStore():void{Auth::requireLogin();if(!can('border.manage')){http_response_code(403);exit;}Csrf::verify();$this->borders->createCustomsBroker($_POST);$this->flash('success','Customs broker added.');$this->redirect('/borders/create');}
    public function packet():void{$this->manage();$record=$this->authorized((int)($_GET['id']??0));$pdf=new SimplePdf();$pdf->rect(36,710,540,50,true,0.92);$companyX=50;$logoRelative=setting('company_logo','');if($logoRelative&&$pdf->image(base_path($logoRelative),50,716,44,36))$companyX=105;$pdf->text($companyX,742,setting('company_name',APP_NAME)?:APP_NAME,17,true);$pdf->text($companyX,724,'Border Crossing Packet',11);$pdf->text(430,742,$record['crossing_number'],13,true);$pdf->text(430,724,date('M d, Y'),9);$y=690;$pdf->text(40,$y,'LOAD & EQUIPMENT',10,true);$pdf->line(40,$y-5,572,$y-5);$y-=24;foreach([['Load',$record['load_number']],['Driver',$record['driver_name']?:'-'],['Truck / Trailer',($record['unit_number']?:'-').' / '.($record['trailer_number']?:'-')],['Route',$record['pickup_location'].' to '.$record['delivery_location']]] as$row){$pdf->text(45,$y,$row[0],9,true);$pdf->wrappedText(150,$y,$row[1],410,9);$y-=22;}$y-=5;$pdf->text(40,$y,'CROSSING DETAILS',10,true);$pdf->line(40,$y-5,572,$y-5);$y-=24;foreach([['Crossing',$record['crossing_name']],['Countries',$record['origin_country'].' → '.$record['destination_country']],['Planned',datetime_display($record['planned_at'])],['Status',readable_status($record['status'])],['Customs Broker',$record['customs_broker_name']?:'-'],['Reference / Entry',($record['reference_number']?:'-').' / '.($record['entry_number']?:'-')],['Seal',$record['seal_number']?:'-']] as$row){$pdf->text(45,$y,$row[0],9,true);$pdf->wrappedText(150,$y,$row[1],410,9);$y-=20;}$y-=8;$pdf->text(40,$y,'DOCUMENT CHECKLIST',10,true);$pdf->line(40,$y-5,572,$y-5);$y-=22;foreach(array_slice($record['checklist'],0,14) as$item){$pdf->text(48,$y,'['.(in_array($item['status'],['approved','waived'],true)?'X':' ').'] '.$item['item_name'],9);$pdf->text(450,$y,readable_status($item['status']),8,true);$y-=16;}$pdf->text(40,55,'Driver instructions: '.($record['driver_instructions']?:'Follow dispatcher and customs broker instructions.'),8);$out=$pdf->output();header('Content-Type: application/pdf');header('Content-Disposition: attachment; filename="'.$record['crossing_number'].'-packet.pdf"');header('Content-Length: '.strlen($out));echo$out;exit;}
    private function authorized(int$id):array{$r=$this->borders->find($id);if(!$r){$this->flash('danger','Border crossing not found.');$this->redirect('/borders');}if(current_role()==='driver'&&(int)$r['driver_id']!==(int)(Auth::user()['driver_id']??0)){http_response_code(403);require app_path('Views/errors/403.php');exit;}return$r;}
}
