<?php
declare(strict_types=1);
require dirname(__DIR__).'/src/bootstrap.php';
require dirname(__DIR__).'/src/domain.php';
require dirname(__DIR__).'/src/actions.php';
require dirname(__DIR__).'/src/pages.php';
header('X-Content-Type-Options: nosniff');
header('X-Frame-Options: DENY');
header('Referrer-Policy: strict-origin-when-cross-origin');
header("Content-Security-Policy: default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; base-uri 'self'; form-action 'self'; frame-ancestors 'none'");

if(isset($_GET['action'])){
    if($_SERVER['REQUEST_METHOD']!=='POST'){http_response_code(405);exit('Méthode non autorisée.');}
    handle_action((string)$_GET['action']);
}

if(isset($_GET['page'])&&$_GET['page']==='preview'){
    $u=require_login();require_permission('sales.view');$id=(int)($_GET['id']??0);$doc=company_record('sales_documents',$id);
    if(!$doc||$doc['status']!=='draft'){http_response_code(404);exit('Aperçu indisponible.');}
    $lines=rows('SELECT * FROM sales_document_lines WHERE document_id=? ORDER BY id',[$id]);$client=company_record('clients',(int)$doc['client_id']);$company=one('SELECT * FROM companies WHERE id=?',[company_id()]);$template=one('SELECT * FROM document_templates WHERE company_id=?',[company_id()])?:['primary_color'=>'#28636B','secondary_color'=>'#E9F0EE','footer_text'=>''];if(!empty($doc['parent_id'])){$parent=company_record('sales_documents',(int)$doc['parent_id']);$doc['parent_number']=$parent['document_number']??null;}$doc['document_number']='APERÇU — NON ÉMIS';
    $preview=render_document_html($doc,$lines,$client?:[],$company?:[],$template);$preview=str_replace('</style>','</style><style>body{padding-top:58px}.preview-banner{position:fixed;z-index:99;top:0;left:0;right:0;background:#173d44;color:white;padding:15px 22px;font:13px Arial,sans-serif;display:flex;justify-content:space-between;align-items:center}.preview-banner a,.preview-banner button{color:#173d44;background:#fff;padding:8px 11px;border:0;border-radius:5px;text-decoration:none;cursor:pointer;margin-left:8px}@media print{body{padding-top:0}.preview-banner{display:none}}</style>', $preview,1);$preview=str_replace('<body>','<body><div class="preview-banner"><span>APERÇU · CE DOCUMENT N’EST PAS ÉMIS</span><span><a href="?page=sales&id='.$id.'">Retour au brouillon</a><button onclick="window.print()">Imprimer l’aperçu</button></span></div>',$preview,1);header('Content-Type: text/html; charset=utf-8');echo $preview;exit;
}

if(isset($_GET['page'])&&$_GET['page']==='download'){
    $u=require_login();$id=(int)($_GET['id']??0);$type=$_GET['type']??'sales';
    if($type==='purchase'){
        require_permission('purchases.view');require_permission('financials.view');$row=one('SELECT document_path,supplier_invoice_number FROM purchases WHERE id=? AND company_id=?',[$id,company_id()]);$relative=$row['document_path']??null;$name='facture-fournisseur-'.($row['supplier_invoice_number']??'document');
    }else{require_permission('sales.view');$row=one('SELECT pdf_path,document_number FROM sales_documents WHERE id=? AND company_id=?',[$id,company_id()]);$relative=$row['pdf_path']??null;$name=$row['document_number']??'document';}
    if(!$relative){http_response_code(404);exit('Fichier indisponible.');}$base=realpath(dirname(__DIR__).'/storage');$file=realpath(dirname(__DIR__).'/storage/'.$relative);if(!$base||!$file||!str_starts_with($file,$base.DIRECTORY_SEPARATOR)||!is_file($file)){http_response_code(404);exit('Fichier introuvable.');}
    header('Cache-Control: private, no-store');header('Content-Type: '.(mime_content_type($file)?:'application/octet-stream'));header('Content-Length: '.filesize($file));header('Content-Disposition: attachment; filename="'.preg_replace('/[^A-Za-z0-9_-]/','_', $name).'.'.pathinfo($file,PATHINFO_EXTENSION).'"');readfile($file);exit;
}

if(!current_user()){render_auth();exit;}
try{render_page();}catch(Throwable $e){error_log((string)$e);$msg=$e instanceof RuntimeException?$e->getMessage():'Une erreur est survenue.';layout('Information','<article class="panel"><h1>Impossible d’afficher cette page</h1><p>'.e($msg).'</p><a href="?page=dashboard">Retour au tableau de bord</a></article>');}
