<?php
class ReportFlag { private $pdo; public function __construct(){ $this->pdo=$GLOBALS['pdo']; }
  public function all(){ return $this->pdo->query("SELECT * FROM report_flags WHERE is_active=1 ORDER BY sort_order ASC, label ASC")->fetchAll(); }
  public function allWithInactive(){ return $this->pdo->query("SELECT * FROM report_flags ORDER BY sort_order ASC, label ASC")->fetchAll(); }
  public function find($id){ $st=$this->pdo->prepare("SELECT * FROM report_flags WHERE id=?"); $st->execute([$id]); return $st->fetch(); }
  public function create($d){ $st=$this->pdo->prepare("INSERT INTO report_flags (code,label,description,view_type,show_additional,show_blocked,sort_order,is_active) VALUES (?,?,?,?,?,?,?,?)"); return $st->execute([$d['code'],$d['label'],$d['description']??'', $d['view_type']??'category_summary', $d['show_additional']??0,$d['show_blocked']??0, $d['sort_order']??0,$d['is_active']??1]); }
  public function update($id,$d){ $st=$this->pdo->prepare("UPDATE report_flags SET code=?, label=?, description=?, view_type=?, show_additional=?, show_blocked=?, sort_order=?, is_active=? WHERE id=?"); return $st->execute([$d['code'],$d['label'],$d['description']??'', $d['view_type']??'category_summary',$d['show_additional']??0,$d['show_blocked']??0,$d['sort_order']??0,$d['is_active']??1,$id]); }
  public function delete($id){ $st=$this->pdo->prepare("DELETE FROM report_flags WHERE id=?"); return $st->execute([$id]); }
  // Override products management
  public function overrides($flagId){ $st=$this->pdo->prepare("SELECT op.*, p.name AS product_name FROM report_flag_override_products op JOIN products p ON p.id=op.product_id WHERE op.report_flag_id=? ORDER BY p.name"); $st->execute([$flagId]); return $st->fetchAll(); }
  public function setOverrides($flagId,$includeIds,$excludeIds){
    $this->pdo->beginTransaction();
    try {
      $this->pdo->prepare("DELETE FROM report_flag_override_products WHERE report_flag_id=?")->execute([$flagId]);
      $ins=$this->pdo->prepare("INSERT INTO report_flag_override_products (report_flag_id,product_id,mode) VALUES (?,?,?)");
      if($includeIds){ foreach($includeIds as $pid){ if(!$pid) continue; $ins->execute([$flagId,$pid,'include']); } }
      if($excludeIds){ foreach($excludeIds as $pid){ if(!$pid) continue; $ins->execute([$flagId,$pid,'exclude']); } }
      $this->pdo->commit();
    } catch(Exception $e){ $this->pdo->rollBack(); throw $e; }
  }
}
