<?php
declare(strict_types=1);
require __DIR__.'/app/bootstrap.php';require_auth();
$pdo=db();$companyId=company_id();$type=(string)($_GET['type']??'');$id=(int)($_GET['id']??0);
if(!$type||!$id){require __DIR__.'/app/layout.php';$docs=[];$queries=[['purchase_order','أمر شراء',"SELECT id,po_no no,order_date doc_date,total_amount amount FROM purchase_orders WHERE company_id=? ORDER BY id DESC LIMIT 30"],['sales_invoice','فاتورة عميل',"SELECT id,invoice_no no,invoice_date doc_date,net_due_amount amount FROM sales_invoices WHERE company_id=? ORDER BY id DESC LIMIT 30"],['supplier_invoice','فاتورة مورد',"SELECT id,internal_no no,invoice_date doc_date,total_amount amount FROM supplier_invoices WHERE company_id=? ORDER BY id DESC LIMIT 30"],['receipt_voucher','سند قبض',"SELECT id,receipt_no no,receipt_date doc_date,amount FROM receipt_vouchers WHERE company_id=? ORDER BY id DESC LIMIT 30"],['payment_voucher','سند صرف',"SELECT id,payment_no no,payment_date doc_date,amount FROM payment_vouchers WHERE company_id=? ORDER BY id DESC LIMIT 30"]];foreach($queries as [$key,$label,$sql]){$q=$pdo->prepare($sql);$q->execute([$companyId]);foreach($q->fetchAll() as $r)$docs[]=[$key,$label,$r];}usort($docs,fn($a,$b)=>strcmp($b[2]['doc_date'],$a[2]['doc_date']));render_header('print','الطباعة والمستندات','نماذج جاهزة للطباعة والحفظ PDF من المتصفح.');?><section class="panel data-card"><div class="responsive-table"><table><thead><tr><th>النوع</th><th>الرقم</th><th>التاريخ</th><th>المبلغ</th><th></th></tr></thead><tbody><?php foreach(array_slice($docs,0,100) as [$key,$label,$r]):?><tr><td><?= e($label) ?></td><td><?= e($r['no']) ?></td><td><?= e($r['doc_date']) ?></td><td><?= number_format((float)$r['amount'],2) ?></td><td><a target="_blank" href="?type=<?= e($key) ?>&id=<?= (int)$r['id'] ?>">طباعة / PDF</a></td></tr><?php endforeach;?></tbody></table></div></section><?php render_footer();exit;}
$company=$pdo->prepare('SELECT * FROM companies WHERE id=?');$company->execute([$companyId]);$company=$company->fetch();$doc=null;$lines=[];$title='';$number='';$date='';$partner='';$project='';$status='';$summary=[];
if($type==='purchase_order'){$q=$pdo->prepare("SELECT po.*,bp.legal_name_ar partner,p.name_ar project_name FROM purchase_orders po JOIN suppliers s ON s.id=po.supplier_id JOIN business_partners bp ON bp.id=s.partner_id LEFT JOIN projects p ON p.id=po.project_id WHERE po.id=? AND po.company_id=?");$q->execute([$id,$companyId]);$doc=$q->fetch();if($doc){$title='أمر شراء';$number=$doc['po_no'];$date=$doc['order_date'];$partner=$doc['partner'];$project=$doc['project_name']?:'عام';$status=$doc['status'];$q=$pdo->prepare('SELECT description,ordered_qty quantity,unit_code,unit_price,tax_amount,total_amount FROM purchase_order_items WHERE purchase_order_id=?');$q->execute([$id]);$lines=$q->fetchAll();$summary=['الإجمالي قبل الضريبة'=>$doc['subtotal'],'الضريبة'=>$doc['tax_amount'],'الإجمالي'=>$doc['total_amount']];}}
elseif($type==='sales_invoice'){$q=$pdo->prepare("SELECT si.*,bp.legal_name_ar partner,p.name_ar project_name FROM sales_invoices si JOIN customers c ON c.id=si.customer_id JOIN business_partners bp ON bp.id=c.partner_id LEFT JOIN projects p ON p.id=si.project_id WHERE si.id=? AND si.company_id=?");$q->execute([$id,$companyId]);$doc=$q->fetch();if($doc){$title='فاتورة عميل';$number=$doc['invoice_no'];$date=$doc['invoice_date'];$partner=$doc['partner'];$project=$doc['project_name']?:'عام';$status=$doc['status'];$q=$pdo->prepare('SELECT description,quantity,unit_code,unit_price,tax_amount,line_total total_amount FROM sales_invoice_items WHERE sales_invoice_id=?');$q->execute([$id]);$lines=$q->fetchAll();$summary=['الإجمالي قبل الضريبة'=>$doc['subtotal'],'الضريبة'=>$doc['tax_amount'],'الإجمالي شامل الضريبة'=>$doc['gross_amount'],'المحتجز'=>$doc['retention_amount'],'الصافي المستحق'=>$doc['net_due_amount']];}}
elseif($type==='supplier_invoice'){$q=$pdo->prepare("SELECT si.*,bp.legal_name_ar partner,p.name_ar project_name FROM supplier_invoices si JOIN suppliers s ON s.id=si.supplier_id JOIN business_partners bp ON bp.id=s.partner_id LEFT JOIN projects p ON p.id=si.project_id WHERE si.id=? AND si.company_id=?");$q->execute([$id,$companyId]);$doc=$q->fetch();if($doc){$title='فاتورة مورد';$number=$doc['internal_no'].' / '.$doc['invoice_no'];$date=$doc['invoice_date'];$partner=$doc['partner'];$project=$doc['project_name']?:'عام';$status=$doc['status'];$q=$pdo->prepare('SELECT description,quantity,unit_code,unit_price,tax_amount,line_total total_amount FROM supplier_invoice_items WHERE supplier_invoice_id=?');$q->execute([$id]);$lines=$q->fetchAll();$summary=['الإجمالي قبل الضريبة'=>$doc['subtotal'],'الضريبة'=>$doc['tax_amount'],'الإجمالي'=>$doc['total_amount'],'المدفوع'=>$doc['paid_amount']];}}
elseif(in_array($type,['receipt_voucher','payment_voucher'],true)){$isReceipt=$type==='receipt_voucher';$table=$isReceipt?'receipt_vouchers':'payment_vouchers';$no=$isReceipt?'receipt_no':'payment_no';$dt=$isReceipt?'receipt_date':'payment_date';$q=$pdo->prepare("SELECT v.*,bp.legal_name_ar partner FROM $table v LEFT JOIN business_partners bp ON bp.id=v.partner_id WHERE v.id=? AND v.company_id=?");$q->execute([$id,$companyId]);$doc=$q->fetch();if($doc){$title=$isReceipt?'سند قبض':'سند صرف';$number=$doc[$no];$date=$doc[$dt];$partner=$doc['partner']?:'—';$project='—';$status=$doc['status'];$summary=['المبلغ'=>$doc['amount']];}}
if(!$doc){http_response_code(404);exit('المستند غير موجود أو لا يتبع الشركة الحالية.');}
?><!doctype html><html lang="ar" dir="rtl"><head><meta charset="utf-8"><title><?= e($title.' '.$number) ?></title><style>body{font-family:Tahoma,Arial;color:#102f2b;margin:30px}.toolbar{display:flex;gap:10px;margin-bottom:20px}.toolbar button{padding:10px 18px}.head{display:flex;justify-content:space-between;border-bottom:3px solid #08796e;padding-bottom:18px}.head h1{margin:0}.company{text-align:left}.meta{display:grid;grid-template-columns:repeat(3,1fr);gap:10px;margin:25px 0}.meta div{border:1px solid #ccd9d7;padding:10px;border-radius:6px}.meta small{display:block;color:#627773}table{width:100%;border-collapse:collapse;margin-top:15px}th,td{border:1px solid #ccd9d7;padding:9px;text-align:right}th{background:#edf6f4}.summary{width:380px;margin-right:auto;margin-top:20px}.summary div{display:flex;justify-content:space-between;border-bottom:1px solid #ccd9d7;padding:8px}.signatures{display:grid;grid-template-columns:repeat(3,1fr);gap:50px;margin-top:70px;text-align:center}.signatures div{border-top:1px solid;padding-top:8px}.note{margin-top:35px;font-size:11px;color:#6b7c79}@media print{.toolbar{display:none}body{margin:10mm}@page{size:A4;margin:12mm}}</style></head><body><div class="toolbar"><button onclick="window.print()">طباعة / حفظ PDF</button><button onclick="window.close()">إغلاق</button></div><header class="head"><div><h1><?= e($title) ?></h1><p><?= e($number) ?></p></div><div class="company"><strong><?= e($company['legal_name_ar']) ?></strong><br>س.ت: <?= e($company['commercial_registration_no']?:'—') ?><br>الرقم الضريبي: <?= e($company['vat_registration_no']?:'—') ?></div></header><section class="meta"><div><small>التاريخ</small><?= e($date) ?></div><div><small>الطرف</small><?= e($partner) ?></div><div><small>المشروع</small><?= e($project) ?></div><div><small>الحالة</small><?= e($status) ?></div><div><small>المرجع</small><?= e($number) ?></div><div><small>العملة</small>ريال سعودي</div></section><?php if($lines):?><table><thead><tr><th>#</th><th>البيان</th><th>الكمية</th><th>الوحدة</th><th>سعر الوحدة</th><th>الضريبة</th><th>الإجمالي</th></tr></thead><tbody><?php foreach($lines as $i=>$l):?><tr><td><?= $i+1 ?></td><td><?= e($l['description']) ?></td><td><?= number_format((float)$l['quantity'],4) ?></td><td><?= e($l['unit_code']) ?></td><td><?= number_format((float)$l['unit_price'],4) ?></td><td><?= number_format((float)$l['tax_amount'],2) ?></td><td><?= number_format((float)$l['total_amount'],2) ?></td></tr><?php endforeach;?></tbody></table><?php endif;?><section class="summary"><?php foreach($summary as $label=>$amount):?><div><span><?= e($label) ?></span><strong><?= number_format((float)$amount,2) ?></strong></div><?php endforeach;?></section><section class="signatures"><div>أعد بواسطة</div><div>راجع بواسطة</div><div>اعتمد بواسطة</div></section><p class="note">مستند صادر من نظام ركائز المالي — تاريخ الطباعة <?= date('Y-m-d H:i') ?></p></body></html>
