<?php
declare(strict_types=1);
require __DIR__.'/app/bootstrap.php';require_permission('dashboard.view_executive');require __DIR__.'/app/layout.php';
$companyId=company_id();
$s=db()->prepare("SELECT COALESCE(SUM(CASE WHEN at.code IN ('REVENUE','OTHER_INCOME') THEN jl.credit_amount-jl.debit_amount ELSE 0 END),0) revenue,COALESCE(SUM(CASE WHEN at.code IN ('COST_OF_REVENUE','EXPENSE','OTHER_EXPENSE') THEN jl.debit_amount-jl.credit_amount ELSE 0 END),0) costs FROM journal_entries je JOIN journal_lines jl ON jl.journal_entry_id=je.id JOIN accounts a ON a.id=jl.account_id JOIN account_types at ON at.id=a.account_type_id WHERE je.company_id=? AND je.status='posted'");$s->execute([$companyId]);$sum=$s->fetch();$revenue=(float)$sum['revenue'];$costs=(float)$sum['costs'];$profit=$revenue-$costs;
$bankOpening=(float)scalar('SELECT COALESCE(SUM(opening_balance),0) FROM bank_accounts WHERE company_id=? AND is_active=1',[$companyId]);$receipts=(float)scalar("SELECT COALESCE(SUM(amount),0) FROM receipt_vouchers WHERE company_id=? AND status='posted'",[$companyId]);$payments=(float)scalar("SELECT COALESCE(SUM(amount),0) FROM payment_vouchers WHERE company_id=? AND status='posted'",[$companyId]);$liquidity=$bankOpening+$receipts-$payments;
$s=db()->prepare("SELECT p.project_no,p.name_ar,COALESCE(SUM(CASE WHEN je.id IS NOT NULL AND at.code IN ('REVENUE','OTHER_INCOME') THEN jl.credit_amount-jl.debit_amount ELSE 0 END),0) revenue,COALESCE(SUM(CASE WHEN je.id IS NOT NULL AND at.code IN ('COST_OF_REVENUE','EXPENSE','OTHER_EXPENSE') THEN jl.debit_amount-jl.credit_amount ELSE 0 END),0) costs FROM projects p LEFT JOIN journal_lines jl ON jl.project_id=p.id LEFT JOIN journal_entries je ON je.id=jl.journal_entry_id AND je.status='posted' LEFT JOIN accounts a ON a.id=jl.account_id LEFT JOIN account_types at ON at.id=a.account_type_id WHERE p.company_id=? AND p.deleted_at IS NULL GROUP BY p.id ORDER BY p.id DESC LIMIT 8");$s->execute([$companyId]);$projectResults=$s->fetchAll();
$pending=[['أوامر شراء بانتظار الاعتماد',(int)scalar("SELECT COUNT(*) FROM purchase_orders WHERE company_id=? AND status='draft'",[$companyId]),'purchases.php'],['مستخلصات عملاء مقدمة',(int)scalar("SELECT COUNT(*) FROM customer_certificates cc JOIN projects p ON p.id=cc.project_id WHERE p.company_id=? AND cc.status='submitted'",[$companyId]),'certificates.php'],['مستخلصات مقاولي باطن مقدمة',(int)scalar("SELECT COUNT(*) FROM subcontract_certificates sc JOIN subcontracts s ON s.id=sc.subcontract_id WHERE s.company_id=? AND sc.status='submitted'",[$companyId]),'certificates.php'],['سندات خزينة بانتظار الاعتماد',(int)scalar("SELECT (SELECT COUNT(*) FROM receipt_vouchers WHERE company_id=? AND status='draft')+(SELECT COUNT(*) FROM payment_vouchers WHERE company_id=? AND status='draft')",[$companyId,$companyId]),'treasury.php']];
$fmt=static fn(float $v):string=>number_format($v,2);render_header('dashboard','نظرة مالية شاملة','مؤشرات فعلية من القيود والسندات المرحلة.');?>
<section class="metrics"><article><i class="tone-teal">◉</i><div><span>الإيرادات المرحلة</span><strong><?= $fmt($revenue) ?> <small>ر.س</small></strong></div></article><article><i class="tone-amber">▤</i><div><span>التكاليف والمصروفات</span><strong><?= $fmt($costs) ?> <small>ر.س</small></strong></div></article><article><i class="tone-green">↗</i><div><span>صافي النتيجة</span><strong><?= $fmt($profit) ?> <small>ر.س</small></strong><em><?= $profit>=0?'ربح':'خسارة' ?></em></div></article><article><i class="tone-blue">▣</i><div><span>السيولة الدفترية</span><strong><?= $fmt($liquidity) ?> <small>ر.س</small></strong></div></article></section>
<section class="dashboard-grid"><article class="panel profit-panel"><header><div><h2>ربحية المشاريع</h2><p>من القيود المرحلة المرتبطة بالمشاريع</p></div></header><?php foreach($projectResults as $p):$margin=(float)$p['revenue']?(((float)$p['revenue']-(float)$p['costs'])/(float)$p['revenue']*100):0;?><div class="profit-row"><span><?= e($p['project_no'].' — '.$p['name_ar']) ?></span><i><b style="width:<?= min(abs($margin),100) ?>%" class="<?= $margin<0?'danger':($margin<10?'warning':'') ?>"></b></i><strong><?= number_format($margin,1) ?>%</strong></div><?php endforeach;?></article><article class="panel"><header><div><h2>ملخص التدفقات</h2><p>حركة الخزينة المرحلة</p></div></header><div class="detail-grid"><div><span>المقبوضات</span><strong><?= $fmt($receipts) ?></strong></div><div><span>المدفوعات</span><strong><?= $fmt($payments) ?></strong></div><div><span>صافي الحركة</span><strong><?= $fmt($receipts-$payments) ?></strong></div><div><span>الأرصدة الافتتاحية</span><strong><?= $fmt($bankOpening) ?></strong></div></div></article></section>
<section class="panel approvals"><header><div><h2>اعتمادات مطلوبة</h2><p>المعاملات التي تنتظر الإجراء</p></div></header><div class="responsive-table"><table><thead><tr><th>المعاملة</th><th>العدد</th><th>الانتقال</th></tr></thead><tbody><?php foreach($pending as [$name,$count,$url]):?><tr><td><?= e($name) ?></td><td><span class="chip <?= $count?'warning':'success' ?>"><?= $count ?></span></td><td><a href="<?= e(app_url($url)) ?>">فتح الوحدة ←</a></td></tr><?php endforeach;?></tbody></table></div></section>
<?php render_footer();
