<?php
declare(strict_types=1);
require __DIR__.'/app/bootstrap.php';require __DIR__.'/app/layout.php';require_auth();
$pdo=db();$companyId=company_id();$userId=(int)user()['id'];
if(!has_permission('finance.periods.close')&&!has_permission('tax.manage')){http_response_code(403);exit('ليس لديك صلاحية للوصول إلى هذه الصفحة.');}
if($_SERVER['REQUEST_METHOD']==='POST'){verify_csrf();try{$action=(string)($_POST['action']??'');
 if($action==='closing_prepare'){if(!has_permission('finance.periods.close'))throw new RuntimeException('لا تملك صلاحية إقفال الفترات.');$periodId=(int)($_POST['period_id']??0);$period=$pdo->prepare("SELECT fp.* FROM fiscal_periods fp JOIN fiscal_years fy ON fy.id=fp.fiscal_year_id WHERE fp.id=? AND fy.company_id=? AND fp.status='open'");$period->execute([$periodId,$companyId]);if(!$period->fetch())throw new RuntimeException('الفترة غير مفتوحة.');if((int)scalar('SELECT COUNT(*) FROM closing_checklists WHERE company_id=? AND fiscal_period_id=?',[$companyId,$periodId]))throw new RuntimeException('توجد قائمة إقفال لهذه الفترة.');$items=['UNPOSTED_JOURNALS'=>'مراجعة القيود غير المرحلة','BANK_RECONCILIATION'=>'إتمام التسويات البنكية','AR_AP_REVIEW'=>'مراجعة أرصدة العملاء والموردين','INVENTORY_CLOSE'=>'مراجعة المخزون والاستلامات','DEPRECIATION'=>'احتساب واعتماد الإهلاك','VAT_REVIEW'=>'مراجعة ضريبة القيمة المضافة'];$pdo->beginTransaction();$pdo->prepare("INSERT INTO closing_checklists(company_id,fiscal_period_id,status,prepared_by,created_at) VALUES (?,?,'in_progress',?,NOW())")->execute([$companyId,$periodId,$userId]);$id=(int)$pdo->lastInsertId();$s=$pdo->prepare('INSERT INTO closing_checklist_items(closing_checklist_id,item_code,item_name_ar,status) VALUES (?,?,?,\'pending\')');foreach($items as $code=>$name)$s->execute([$id,$code,$name]);$pdo->commit();audit('period_closing.prepare','closing_checklist',(string)$id);flash('success','تم إنشاء قائمة إقفال الفترة.');
 }elseif($action==='closing_item'){if(!has_permission('finance.periods.close'))throw new RuntimeException('لا تملك صلاحية إقفال الفترات.');$id=(int)($_POST['id']??0);$status=(string)($_POST['status']??'completed');if(!in_array($status,['completed','waived','blocked'],true))throw new RuntimeException('حالة البند غير صالحة.');$s=$pdo->prepare("UPDATE closing_checklist_items ci JOIN closing_checklists cc ON cc.id=ci.closing_checklist_id SET ci.status=?,ci.completed_by=?,ci.completed_at=IF(? IN ('completed','waived'),NOW(),NULL),ci.notes=? WHERE ci.id=? AND cc.company_id=? AND cc.status IN ('draft','in_progress')");$s->execute([$status,$userId,$status,trim((string)($_POST['notes']??''))?:null,$id,$companyId]);if(!$s->rowCount())throw new RuntimeException('تعذر تحديث بند الإقفال.');$checkId=(int)scalar('SELECT closing_checklist_id FROM closing_checklist_items WHERE id=?',[$id]);$pending=(int)scalar("SELECT COUNT(*) FROM closing_checklist_items WHERE closing_checklist_id=? AND status NOT IN ('completed','waived')",[$checkId]);if(!$pending){$pdo->prepare("UPDATE closing_checklists SET status='ready',reviewed_by=? WHERE id=?")->execute([$userId,$checkId]);$pdo->prepare("UPDATE fiscal_periods fp JOIN closing_checklists cc ON cc.fiscal_period_id=fp.id SET fp.status='soft_closed' WHERE cc.id=? AND fp.status='open'")->execute([$checkId]);}audit('period_closing.item','closing_checklist_item',(string)$id,['status'=>$status]);flash('success',$pending?'تم تحديث بند الإقفال.':'اكتملت القائمة وأصبحت الفترة مقفلة مبدئيًا.');
 }elseif($action==='closing_finalize'){if(!has_permission('finance.periods.close'))throw new RuntimeException('لا تملك صلاحية إقفال الفترات.');$id=(int)($_POST['id']??0);$q=$pdo->prepare("SELECT cc.*,fp.fiscal_year_id FROM closing_checklists cc JOIN fiscal_periods fp ON fp.id=cc.fiscal_period_id WHERE cc.id=? AND cc.company_id=? AND cc.status='ready' AND fp.status='soft_closed'");$q->execute([$id,$companyId]);$check=$q->fetch();if(!$check)throw new RuntimeException('قائمة الإقفال غير جاهزة.');$pdo->beginTransaction();$pdo->prepare("UPDATE fiscal_periods SET status='closed',closed_at=NOW(),closed_by=? WHERE id=?")->execute([$userId,$check['fiscal_period_id']]);$pdo->prepare("UPDATE closing_checklists SET status='closed',closed_at=NOW(),reviewed_by=? WHERE id=?")->execute([$userId,$id]);$remaining=(int)scalar("SELECT COUNT(*) FROM fiscal_periods WHERE fiscal_year_id=? AND status<>'closed'",[$check['fiscal_year_id']]);$pdo->prepare("UPDATE fiscal_years SET status=?,closed_at=IF(?=0,NOW(),closed_at),closed_by=IF(?=0,?,closed_by) WHERE id=? AND company_id=?")->execute([$remaining?'soft_closed':'closed',$remaining,$remaining,$userId,$check['fiscal_year_id'],$companyId]);$pdo->commit();audit('period_closing.finalize','closing_checklist',(string)$id);flash('success','تم الإقفال النهائي للفترة ومنع الترحيل عليها.');
 }elseif($action==='tax_period_create'){if(!has_permission('tax.manage'))throw new RuntimeException('لا تملك صلاحية إدارة الضريبة.');$from=(string)$_POST['period_from'];$to=(string)$_POST['period_to'];if(!$from||!$to||$from>$to)throw new RuntimeException('الفترة الضريبية غير صحيحة.');$s=$pdo->prepare("INSERT INTO tax_periods(company_id,tax_type,period_from,period_to,filing_due_date,payment_due_date,status) VALUES (?,'vat',?,?,?,?, 'open')");$s->execute([$companyId,$from,$to,($_POST['filing_due_date']??'')?:null,($_POST['payment_due_date']??'')?:null]);audit('tax_period.create','tax_period',(string)$pdo->lastInsertId());flash('success','تم إنشاء الفترة الضريبية.');
 }elseif($action==='tax_prepare'){if(!has_permission('tax.manage'))throw new RuntimeException('لا تملك صلاحية إدارة الضريبة.');$periodId=(int)($_POST['period_id']??0);$q=$pdo->prepare("SELECT * FROM tax_periods WHERE id=? AND company_id=? AND tax_type='vat' AND status='open'");$q->execute([$periodId,$companyId]);$period=$q->fetch();if(!$period)throw new RuntimeException('الفترة الضريبية غير متاحة.');if((int)scalar('SELECT COUNT(*) FROM tax_returns WHERE tax_period_id=?',[$periodId]))throw new RuntimeException('تم إعداد إقرار لهذه الفترة.');$salesBase=(float)scalar("SELECT COALESCE(SUM(subtotal),0) FROM sales_invoices WHERE company_id=? AND invoice_date BETWEEN ? AND ? AND status IN ('issued','partially_collected','collected','overdue')",[$companyId,$period['period_from'],$period['period_to']]);$output=(float)scalar("SELECT COALESCE(SUM(tax_amount),0) FROM sales_invoices WHERE company_id=? AND invoice_date BETWEEN ? AND ? AND status IN ('issued','partially_collected','collected','overdue')",[$companyId,$period['period_from'],$period['period_to']]);$purchaseBase=(float)scalar("SELECT COALESCE(SUM(subtotal),0) FROM supplier_invoices WHERE company_id=? AND invoice_date BETWEEN ? AND ? AND status IN ('posted','partially_paid','paid')",[$companyId,$period['period_from'],$period['period_to']]);$input=(float)scalar("SELECT COALESCE(SUM(tax_amount),0) FROM supplier_invoices WHERE company_id=? AND invoice_date BETWEEN ? AND ? AND status IN ('posted','partially_paid','paid')",[$companyId,$period['period_from'],$period['period_to']]);$pdo->beginTransaction();$no='VAT-'.date('Ym',strtotime($period['period_to']));$pdo->prepare("INSERT INTO tax_returns(tax_period_id,return_no,output_tax,input_tax,net_tax_due,status,prepared_by,created_at,updated_at) VALUES (?,?,?,?,?,'draft',?,NOW(),NOW())")->execute([$periodId,$no,$output,$input,$output-$input,$userId]);$returnId=(int)$pdo->lastInsertId();$s=$pdo->prepare('INSERT INTO tax_return_lines(tax_return_id,line_code,description,taxable_base,tax_amount,source_count) VALUES (?,?,?,?,?,?)');$s->execute([$returnId,'SALES_STD','المبيعات الخاضعة للضريبة',$salesBase,$output,(int)scalar("SELECT COUNT(*) FROM sales_invoices WHERE company_id=? AND invoice_date BETWEEN ? AND ? AND status IN ('issued','partially_collected','collected','overdue')",[$companyId,$period['period_from'],$period['period_to']])]);$s->execute([$returnId,'PURCHASES_STD','المشتريات القابلة للخصم',$purchaseBase,$input,(int)scalar("SELECT COUNT(*) FROM supplier_invoices WHERE company_id=? AND invoice_date BETWEEN ? AND ? AND status IN ('posted','partially_paid','paid')",[$companyId,$period['period_from'],$period['period_to']])]);$pdo->prepare("UPDATE tax_periods SET status='prepared' WHERE id=?")->execute([$periodId]);$pdo->commit();audit('tax_return.prepare','tax_return',(string)$returnId);flash('success','تم احتساب إقرار الضريبة: صافي مستحق '.number_format($output-$input,2));
 }elseif(in_array($action,['tax_review','tax_approve','tax_file','tax_pay'],true)){if(!has_permission('tax.manage'))throw new RuntimeException('لا تملك صلاحية إدارة الضريبة.');$id=(int)($_POST['id']??0);if($action==='tax_review')$s=$pdo->prepare("UPDATE tax_returns tr JOIN tax_periods tp ON tp.id=tr.tax_period_id SET tr.status='reviewed',tr.reviewed_by=? WHERE tr.id=? AND tp.company_id=? AND tr.status='draft'");elseif($action==='tax_approve')$s=$pdo->prepare("UPDATE tax_returns tr JOIN tax_periods tp ON tp.id=tr.tax_period_id SET tr.status='approved',tr.approved_by=? WHERE tr.id=? AND tp.company_id=? AND tr.status='reviewed'");elseif($action==='tax_file')$s=$pdo->prepare("UPDATE tax_returns tr JOIN tax_periods tp ON tp.id=tr.tax_period_id SET tr.status='filed',tr.filed_at=NOW(),tr.filed_reference=?,tp.status='filed' WHERE tr.id=? AND tp.company_id=? AND tr.status='approved'");else $s=$pdo->prepare("UPDATE tax_returns tr JOIN tax_periods tp ON tp.id=tr.tax_period_id SET tr.status='paid',tp.status='paid' WHERE tr.id=? AND tp.company_id=? AND tr.status='filed'");if($action==='tax_file')$s->execute([trim((string)($_POST['filed_reference']??''))?:null,$id,$companyId]);elseif(in_array($action,['tax_review','tax_approve'],true))$s->execute([$userId,$id,$companyId]);else $s->execute([$id,$companyId]);if(!$s->rowCount())throw new RuntimeException('تعذر تغيير حالة الإقرار.');audit($action,'tax_return',(string)$id);flash('success','تم تحديث حالة الإقرار الضريبي.');
 }}catch(Throwable $e){if($pdo->inTransaction())$pdo->rollBack();flash('error',$e instanceof PDOException?'تعذر الحفظ؛ الفترة أو الإقرار مكرر.':$e->getMessage());}redirect('compliance.php');}
$periods=$pdo->prepare("SELECT fp.*,fy.name year_name FROM fiscal_periods fp JOIN fiscal_years fy ON fy.id=fp.fiscal_year_id WHERE fy.company_id=? ORDER BY fp.starts_on DESC");$periods->execute([$companyId]);$periods=$periods->fetchAll();$closings=$pdo->prepare("SELECT cc.*,fp.name period_name,fy.name year_name,(SELECT COUNT(*) FROM closing_checklist_items ci WHERE ci.closing_checklist_id=cc.id AND ci.status IN ('completed','waived')) completed_count,(SELECT COUNT(*) FROM closing_checklist_items ci WHERE ci.closing_checklist_id=cc.id) total_count FROM closing_checklists cc JOIN fiscal_periods fp ON fp.id=cc.fiscal_period_id JOIN fiscal_years fy ON fy.id=fp.fiscal_year_id WHERE cc.company_id=? ORDER BY cc.id DESC");$closings->execute([$companyId]);$closings=$closings->fetchAll();$selectedClosing=(int)($_GET['closing_id']??0);$closingItems=[];if($selectedClosing){$s=$pdo->prepare('SELECT ci.* FROM closing_checklist_items ci JOIN closing_checklists cc ON cc.id=ci.closing_checklist_id WHERE ci.closing_checklist_id=? AND cc.company_id=? ORDER BY ci.id');$s->execute([$selectedClosing,$companyId]);$closingItems=$s->fetchAll();}$taxPeriods=$pdo->prepare('SELECT * FROM tax_periods WHERE company_id=? AND tax_type=\'vat\' ORDER BY period_from DESC');$taxPeriods->execute([$companyId]);$taxPeriods=$taxPeriods->fetchAll();$returns=$pdo->prepare('SELECT tr.*,tp.period_from,tp.period_to FROM tax_returns tr JOIN tax_periods tp ON tp.id=tr.tax_period_id WHERE tp.company_id=? ORDER BY tr.id DESC');$returns->execute([$companyId]);$returns=$returns->fetchAll();
render_header('compliance','الإقفال والامتثال الضريبي','قوائم إقفال الفترات وإعداد إقرار ضريبة القيمة المضافة.');?>
<?php if(has_permission('finance.periods.close')):?><details class="panel quick-add"><summary>＋ بدء إقفال فترة</summary><form method="post"><?= csrf_field() ?><input type="hidden" name="action" value="closing_prepare"><label>الفترة المفتوحة<select name="period_id"><?php foreach($periods as $p)if($p['status']==='open'):?><option value="<?= (int)$p['id'] ?>"><?= e($p['year_name'].' — '.$p['name']) ?></option><?php endif;?></select></label><button class="primary-btn">إنشاء قائمة الإقفال</button></form></details>
<section class="panel data-card"><header><h2>إقفالات الفترات</h2></header><div class="responsive-table"><table><thead><tr><th>الفترة</th><th>المنجز</th><th>الحالة</th><th></th></tr></thead><tbody><?php foreach($closings as $c):?><tr><td><?= e($c['year_name'].' — '.$c['period_name']) ?></td><td><?= (int)$c['completed_count'] ?> / <?= (int)$c['total_count'] ?></td><td><span class="chip"><?= e($c['status']) ?></span></td><td><a href="?closing_id=<?= (int)$c['id'] ?>">القائمة</a><?php if($c['status']==='ready'):?><form method="post"><?= csrf_field() ?><input type="hidden" name="action" value="closing_finalize"><input type="hidden" name="id" value="<?= (int)$c['id'] ?>"><button>إقفال نهائي</button></form><?php endif;?></td></tr><?php endforeach;?></tbody></table></div></section>
<?php if($closingItems):?><section class="panel data-card"><header><h2>قائمة مراجعة الإقفال</h2></header><div class="responsive-table"><table><thead><tr><th>البند</th><th>الحالة</th><th>ملاحظات</th><th>تحديث</th></tr></thead><tbody><?php foreach($closingItems as $i):?><tr><td><?= e($i['item_name_ar']) ?></td><td><span class="chip"><?= e($i['status']) ?></span></td><td><?= e($i['notes']?:'—') ?></td><td><?php if(in_array($i['status'],['pending','blocked'],true)):?><form method="post"><?= csrf_field() ?><input type="hidden" name="action" value="closing_item"><input type="hidden" name="id" value="<?= (int)$i['id'] ?>"><select name="status"><option value="completed">مكتمل</option><option value="waived">مستثنى</option><option value="blocked">متعثر</option></select><input name="notes" placeholder="ملاحظة"><button>حفظ</button></form><?php endif;?></td></tr><?php endforeach;?></tbody></table></div></section><?php endif;endif;?>
<?php if(has_permission('tax.manage')):?><div class="settings-grid"><details class="panel quick-add"><summary>＋ فترة ضريبية</summary><form method="post"><?= csrf_field() ?><input type="hidden" name="action" value="tax_period_create"><label>من<input type="date" name="period_from" required></label><label>إلى<input type="date" name="period_to" required></label><label>موعد التقديم<input type="date" name="filing_due_date"></label><label>موعد السداد<input type="date" name="payment_due_date"></label><button class="primary-btn">حفظ الفترة</button></form></details><section class="panel form-card"><h2>إعداد الإقرار</h2><form method="post"><?= csrf_field() ?><input type="hidden" name="action" value="tax_prepare"><label>الفترة المفتوحة<select name="period_id"><?php foreach($taxPeriods as $p)if($p['status']==='open'):?><option value="<?= (int)$p['id'] ?>"><?= e($p['period_from'].' إلى '.$p['period_to']) ?></option><?php endif;?></select></label><button class="primary-btn">احتساب الإقرار</button></form></section></div>
<section class="panel data-card"><header><h2>إقرارات ضريبة القيمة المضافة</h2></header><div class="responsive-table"><table><thead><tr><th>الإقرار</th><th>الفترة</th><th>المخرجات</th><th>المدخلات</th><th>الصافي</th><th>الحالة</th><th>الإجراء</th></tr></thead><tbody><?php foreach($returns as $r):?><tr><td><?= e($r['return_no']?:'—') ?></td><td><?= e($r['period_from'].' إلى '.$r['period_to']) ?></td><td><?= number_format((float)$r['output_tax'],2) ?></td><td><?= number_format((float)$r['input_tax'],2) ?></td><td><?= number_format((float)$r['net_tax_due'],2) ?></td><td><span class="chip"><?= e($r['status']) ?></span></td><td><?php $next=$r['status']==='draft'?'tax_review':($r['status']==='reviewed'?'tax_approve':($r['status']==='approved'?'tax_file':($r['status']==='filed'?'tax_pay':'')));$labels=['tax_review'=>'مراجعة','tax_approve'=>'اعتماد','tax_file'=>'تقديم','tax_pay'=>'تسجيل السداد'];if($next):?><form method="post"><?= csrf_field() ?><input type="hidden" name="action" value="<?= $next ?>"><input type="hidden" name="id" value="<?= (int)$r['id'] ?>"><?php if($next==='tax_file'):?><input name="filed_reference" placeholder="مرجع الهيئة" required><?php endif;?><button><?= e($labels[$next]) ?></button></form><?php endif;?></td></tr><?php endforeach;?></tbody></table></div></section><?php endif;?>
<?php render_footer();
