<?php
require_once '../app/Models/ReportFlag.php';
class ReportFlagController { private $m; public function __construct(){ $this->auth(); $this->m=new ReportFlag(); }
  private function auth(){ if(!isset($_SESSION['user_id'])){ redirect('login'); exit; } }
  public function index(){ $this->view('report_flags/index',['flags'=>$this->m->allWithInactive()]); }
  public function create(){ $this->view('report_flags/create'); }
  public function store(){ if($_SERVER['REQUEST_METHOD']!=='POST'){ redirect('report-flags'); exit; } $code=trim($_POST['code']??''); $label=trim($_POST['label']??''); if($code===''||$label===''){ $_SESSION['error']='Code & Label required'; redirect('report-flags/create'); exit; } $this->m->create(['code'=>$code,'label'=>$label,'description'=>$_POST['description']??'','view_type'=>$_POST['view_type']??'category_summary','show_additional'=>isset($_POST['show_additional'])?1:0,'show_blocked'=>isset($_POST['show_blocked'])?1:0,'sort_order'=>$_POST['sort_order']??0,'is_active'=>isset($_POST['is_active'])?1:0]); $_SESSION['success']='Flag created'; redirect('report-flags'); }
  public function edit($id){ $u=$this->m->find($id); if(!$u){ $_SESSION['error']='Not found'; redirect('report-flags'); exit; } $overrides=$this->m->overrides($id); $products=$this->allProducts(); $byMode=['include'=>[],'exclude'=>[]]; foreach($overrides as $o){ $byMode[$o['mode']][]=$o['product_id']; } $this->view('report_flags/edit',['flag'=>$u,'products'=>$products,'overrideInclude'=>$byMode['include'],'overrideExclude'=>$byMode['exclude']]); }
  public function update($id){ if($_SERVER['REQUEST_METHOD']!=='POST'){ redirect('report-flags'); exit; } $this->m->update($id,['code'=>$_POST['code'],'label'=>$_POST['label'],'description'=>$_POST['description']??'','view_type'=>$_POST['view_type']??'category_summary','show_additional'=>isset($_POST['show_additional'])?1:0,'show_blocked'=>isset($_POST['show_blocked'])?1:0,'sort_order'=>$_POST['sort_order']??0,'is_active'=>isset($_POST['is_active'])?1:0]); $include=$_POST['override_include']??[]; $exclude=$_POST['override_exclude']??[]; $this->m->setOverrides($id,$include,$exclude); $_SESSION['success']='Updated'; redirect('report-flags'); }
  private function allProducts(){ return $GLOBALS['pdo']->query("SELECT id,name FROM products ORDER BY name")->fetchAll(); }
  public function delete($id){ if($_SERVER['REQUEST_METHOD']!=='POST'){ redirect('report-flags'); exit; } $this->m->delete($id); $_SESSION['success']='Deleted'; redirect('report-flags'); }
  private function view($v,$d=[]){ extract($d); require_once "../app/Views/$v.php"; }
}


