<?php
$page_title = 'الفوترة والمحاسبة | Billing & Accounting';
$UA_FORCE_DESIGN_V2 = true;
require_once __DIR__ . '/finance_expense_lib.php';
require_login('login.php');
if (function_exists('require_perm')) require_perm('can_view_reports');
finance_expense_migrate($conn);

$uaAndroidFinanceReports = ((string)($_GET['ua_android'] ?? '') === '1')
  || stripos((string)($_SERVER['HTTP_USER_AGENT'] ?? ''), 'NetworkCustomersAndroid/') !== false;
$UA_PAGE_CSS = [$uaAndroidFinanceReports ? 'assets/css/android_finance_reports.css' : 'assets/css/finance_dashboard.css'];

$start = preg_match('~^\d{4}-\d{2}-\d{2}$~', (string)($_GET['start'] ?? '')) ? (string)$_GET['start'] : date('Y-m-01');
$end = preg_match('~^\d{4}-\d{2}-\d{2}$~', (string)($_GET['end'] ?? '')) ? (string)$_GET['end'] : date('Y-m-t');
if ($start > $end) [$start,$end]=[$end,$start];

$sum_invoices=$sum_paid=$sum_remaining=$sum_expenses=$purchase_syp=$purchase_usd=0.0;
$invoice_count=$paid_invoice_count=$unpaid_invoice_count=$overdue_invoice_count=0;
$invTotal=finance_table_exists($conn,'invoices')?finance_pick_col($conn,'invoices',['total_amount','amount','total','price','invoice_total']):null;
$invDate=finance_table_exists($conn,'invoices')?finance_pick_col($conn,'invoices',['invoice_date','date','created_at','issued_at']):null;
$hasRemaining=finance_table_exists($conn,'invoices')&&finance_column_exists($conn,'invoices','remaining_amount');
if($invTotal&&$invDate){
  $paidExpr=finance_column_exists($conn,'invoices','payment_status')?"LOWER(COALESCE(payment_status,'')) IN ('paid','settled')":"LOWER(COALESCE(status,'')) IN ('paid','مدفوع')";
  $remainingExpr=$hasRemaining?'COALESCE(remaining_amount,0)':"CASE WHEN {$paidExpr} THEN 0 ELSE COALESCE({$invTotal},0) END";
  $dueExpr=finance_column_exists($conn,'invoices','due_date')?"COALESCE(due_date,DATE({$invDate}))":"DATE({$invDate})";
  $st=$conn->prepare("SELECT COALESCE(SUM(COALESCE({$invTotal},0)),0) total,COUNT(*) cnt,
    SUM(CASE WHEN {$paidExpr} THEN 1 ELSE 0 END) paid_cnt,
    SUM(CASE WHEN NOT({$paidExpr}) AND {$remainingExpr}>0 THEN 1 ELSE 0 END) unpaid_cnt,
    SUM(CASE WHEN NOT({$paidExpr}) AND {$remainingExpr}>0 AND {$dueExpr}<CURDATE() THEN 1 ELSE 0 END) overdue_cnt,
    COALESCE(SUM({$remainingExpr}),0) remaining_total
    FROM invoices WHERE DATE({$invDate}) BETWEEN ? AND ?");
  $st->bind_param('ss',$start,$end);$st->execute();$row=$st->get_result()->fetch_assoc();$st->close();
  $sum_invoices=(float)($row['total']??0);$invoice_count=(int)($row['cnt']??0);$paid_invoice_count=(int)($row['paid_cnt']??0);
  $unpaid_invoice_count=(int)($row['unpaid_cnt']??0);$overdue_invoice_count=(int)($row['overdue_cnt']??0);$sum_remaining=(float)($row['remaining_total']??0);
}

$postedFilter=finance_table_exists($conn,'payments')&&finance_column_exists($conn,'payments','payment_status')?" AND COALESCE(payment_status,'POSTED')='POSTED'":'';
if(finance_table_exists($conn,'payments')){
  $st=$conn->prepare("SELECT COALESCE(SUM(amount),0) total FROM payments WHERE DATE(COALESCE(paid_at,created_at)) BETWEEN ? AND ?{$postedFilter}");
  $st->bind_param('ss',$start,$end);$st->execute();$sum_paid=(float)($st->get_result()->fetch_assoc()['total']??0);$st->close();
}
if(finance_table_exists($conn,'expenses')){
  $st=$conn->prepare("SELECT COALESCE(SUM(amount),0) total FROM expenses WHERE DATE(COALESCE(spent_at,expense_date)) BETWEEN ? AND ? AND COALESCE(expense_status,'POSTED')='POSTED'");
  $st->bind_param('ss',$start,$end);$st->execute();$sum_expenses=(float)($st->get_result()->fetch_assoc()['total']??0);$st->close();
}
if(finance_table_exists($conn,'shop_purchases')){
  $st=$conn->prepare("SELECT COALESCE(SUM(CASE WHEN UPPER(COALESCE(currency,'SYP'))='USD' THEN total ELSE 0 END),0) usd_total,
    COALESCE(SUM(CASE WHEN UPPER(COALESCE(currency,'SYP'))<>'USD' THEN total ELSE 0 END),0) syp_total FROM shop_purchases WHERE DATE(created_at) BETWEEN ? AND ?");
  $st->bind_param('ss',$start,$end);$st->execute();$row=$st->get_result()->fetch_assoc();$st->close();$purchase_syp=(float)$row['syp_total'];$purchase_usd=(float)$row['usd_total'];
}
$net=$sum_paid-$sum_expenses;
$collection_rate=$sum_invoices>0?min(100,max(0,$sum_paid/$sum_invoices*100)):0.0;

$by_method=[];
if(finance_table_exists($conn,'payments')){
  $st=$conn->prepare("SELECT COALESCE(NULLIF(method,''),'غير محدد') label,SUM(amount) total FROM payments WHERE DATE(COALESCE(paid_at,created_at)) BETWEEN ? AND ?{$postedFilter} GROUP BY label ORDER BY total DESC");
  $st->bind_param('ss',$start,$end);$st->execute();$rs=$st->get_result();while($rs&&($row=$rs->fetch_assoc()))$by_method[]=$row;$st->close();
}
$by_category=[];
if(finance_table_exists($conn,'expenses')){
  $st=$conn->prepare("SELECT COALESCE(t.name,NULLIF(e.category,''),'غير مصنف') label,SUM(e.amount) total FROM expenses e LEFT JOIN expense_types t ON t.id=e.expense_type_id WHERE DATE(COALESCE(e.spent_at,e.expense_date)) BETWEEN ? AND ? AND COALESCE(e.expense_status,'POSTED')='POSTED' GROUP BY label ORDER BY total DESC");
  $st->bind_param('ss',$start,$end);$st->execute();$rs=$st->get_result();while($rs&&($row=$rs->fetch_assoc()))$by_category[]=$row;$st->close();
}
$by_source=[];
if(finance_table_exists($conn,'payments')){
  $st=$conn->prepare("SELECT COALESCE(NULLIF(collection_source_type,''),'main') source_type,COALESCE(NULLIF(collection_source_ref,''),'main') source_ref,
    COALESCE(NULLIF(collection_source_name,''),'النسخة الرئيسية') source_name,SUM(amount) total,COUNT(*) payment_count
    FROM payments WHERE DATE(COALESCE(paid_at,created_at)) BETWEEN ? AND ?{$postedFilter} GROUP BY source_type,source_ref,source_name ORDER BY total DESC");
  $st->bind_param('ss',$start,$end);$st->execute();$rs=$st->get_result();while($rs&&($row=$rs->fetch_assoc()))$by_source[]=$row;$st->close();
}

$daily=[];$dailyEnd=min($end,date('Y-m-d'));$cursor=$start;
while($cursor<=$dailyEnd){$daily[$cursor]=['day'=>$cursor,'in'=>0.0,'out'=>0.0,'net'=>0.0];$cursor=date('Y-m-d',strtotime($cursor.' +1 day'));}
if($daily&&finance_table_exists($conn,'payments')){
  $st=$conn->prepare("SELECT DATE(COALESCE(paid_at,created_at)) day,SUM(amount) total FROM payments WHERE DATE(COALESCE(paid_at,created_at)) BETWEEN ? AND ?{$postedFilter} GROUP BY day");
  $st->bind_param('ss',$start,$dailyEnd);$st->execute();$rs=$st->get_result();while($rs&&($row=$rs->fetch_assoc()))if(isset($daily[$row['day']]))$daily[$row['day']]['in']=(float)$row['total'];$st->close();
}
if($daily&&finance_table_exists($conn,'expenses')){
  $st=$conn->prepare("SELECT DATE(COALESCE(spent_at,expense_date)) day,SUM(amount) total FROM expenses WHERE DATE(COALESCE(spent_at,expense_date)) BETWEEN ? AND ? AND COALESCE(expense_status,'POSTED')='POSTED' GROUP BY day");
  $st->bind_param('ss',$start,$dailyEnd);$st->execute();$rs=$st->get_result();while($rs&&($row=$rs->fetch_assoc()))if(isset($daily[$row['day']]))$daily[$row['day']]['out']=(float)$row['total'];$st->close();
}
foreach($daily as &$item)$item['net']=$item['in']-$item['out'];unset($item);
$daily_recent=array_slice(array_values($daily),-14);$daily_max=1.0;foreach($daily_recent as $item)$daily_max=max($daily_max,(float)$item['in'],(float)$item['out']);
$today_cashboxes=finance_daily_view($conn,date('Y-m-d'));$cashbox_final_total=array_sum(array_column($today_cashboxes,'final'));
$typeLabels=['main'=>'رئيسية','branch'=>'فرعية','agent'=>'مندوب'];

include __DIR__.'/header.php';include __DIR__.'/sidebar.php';
$finance_active='summary';$finance_group='summary';
if($uaAndroidFinanceReports){require __DIR__.'/android_finance_reports.php';include __DIR__.'/footer.php';return;}
?>
<div class="content-wrapper ua-extracted-page fin-dashboard"><section class="content"><div class="container-fluid">
  <?php include __DIR__.'/finance_tabs.php'; ?>
  <header class="fin-dash-hero"><div><span>Billing & Accounting</span><h1>الفوترة والمحاسبة</h1></div><div class="fin-dash-actions"><a href="invoices_add.php"><i class="fa fa-plus"></i> فاتورة جديدة</a><a href="finance_payments.php"><i class="fa fa-money"></i> تسجيل دفعة</a><a href="finance_expenses.php"><i class="fa fa-arrow-up"></i> إضافة مصروف</a><a href="finance_partners.php"><i class="fa fa-users"></i> الشركاء ورأس المال</a></div></header>
  <nav class="fin-module-nav" aria-label="أقسام الفوترة والمحاسبة"><a href="invoices.php"><i class="fa fa-file-text-o"></i><span>الفواتير</span></a><a href="finance_payments.php"><i class="fa fa-arrow-circle-down"></i><span>الدفعات</span></a><a href="finance_expenses.php"><i class="fa fa-arrow-circle-up"></i><span>المصروفات</span></a><a href="finance_daily_balances.php"><i class="fa fa-archive"></i><span>الصناديق</span></a><a href="purchases_report.php"><i class="fa fa-shopping-bag"></i><span>المشتريات</span></a><a href="finance_partners.php"><i class="fa fa-users"></i><span>الشركاء ورأس المال</span></a><a href="billing_message_requests.php"><i class="fa fa-envelope"></i><span>رسائل التسديد</span></a></nav>
  <form class="fin-period" method="get"><div><label>من تاريخ</label><input type="date" name="start" value="<?=h($start)?>"></div><div><label>إلى تاريخ</label><input type="date" name="end" value="<?=h($end)?>"></div><button><i class="fa fa-filter"></i> تطبيق الفترة</button><a href="finance_reports.php">هذا الشهر</a></form>
  <section class="fin-kpi-grid">
    <?php $kpis=[
      ['fa-file-text-o','إجمالي الفواتير',$sum_invoices,$invoice_count.' فاتورة','blue'],['fa-check-circle','المقبوضات',$sum_paid,$paid_invoice_count.' فاتورة مسددة','green'],
      ['fa-hourglass-half','الذمم المتبقية',$sum_remaining,$unpaid_invoice_count.' فاتورة غير مسددة','amber'],['fa-exclamation-triangle','الفواتير المتأخرة',$overdue_invoice_count, 'فاتورة تجاوزت الاستحقاق','red','count'],
      ['fa-arrow-circle-up','المصروفات',$sum_expenses,'خلال الفترة','red'],['fa-line-chart','صافي الحركة',$net,'مقبوضات ناقص المصروفات',$net>=0?'green':'red']]; ?>
    <?php foreach($kpis as $k): ?><article class="is-<?=$k[4]?>"><i class="fa <?=$k[0]?>"></i><span><?=$k[1]?></span><strong dir="ltr"><?=isset($k[5])?(int)$k[2]:number_format((float)$k[2],2)?></strong><small><?=$k[3]?></small></article><?php endforeach; ?>
  </section>
  <section class="fin-health-grid"><article class="fin-collection"><header><div><span>كفاءة التحصيل</span><strong><?=number_format($collection_rate,1)?>%</strong></div><a href="invoices.php">عرض الفواتير</a></header><div class="fin-progress"><i style="width:<?=number_format($collection_rate,2,'.','')?>%"></i></div><p>تم تحصيل <?=number_format($sum_paid,2)?> من أصل <?=number_format($sum_invoices,2)?> ضمن الفترة.</p></article><article><span>رصيد صناديق اليوم</span><strong dir="ltr"><?=number_format($cashbox_final_total,2)?></strong><small><?=count($today_cashboxes)?> صندوق / نسخة</small><a href="finance_daily_balances.php">فتح الأرصدة اليومية</a></article><article><span>المشتريات SYP</span><strong dir="ltr"><?=number_format($purchase_syp,2)?></strong><small>المشتريات المسجلة خلال الفترة</small><a href="purchases_report.php">سجل المشتريات</a></article><article><span>المشتريات USD</span><strong dir="ltr"><?=number_format($purchase_usd,2)?></strong><small>مفصولة عن العملة المحلية</small><a href="purchases_report.php">فتح الجرد</a></article></section>
  <div class="fin-dashboard-grid">
    <section class="fin-panel fin-panel--wide"><header><div><span>Collections by source</span><h2>التحصيل حسب النسخة أو المندوب</h2></div><a href="finance_daily_balances.php">الأرصدة اليومية</a></header><div class="fin-source-list"><?php foreach($by_source as $row): ?><article><i class="fa <?=$row['source_type']==='agent'?'fa-user':($row['source_type']==='branch'?'fa-sitemap':'fa-building')?>"></i><div><b><?=h($row['source_name'])?></b><small><?=h($typeLabels[$row['source_type']]??$row['source_type'])?> · <?=h($row['source_ref'])?></small></div><span><?=number_format((float)$row['total'],2)?><small><?=(int)$row['payment_count']?> دفعة</small></span></article><?php endforeach; ?><?php if(!$by_source): ?><p class="fin-empty">لا توجد عمليات تحصيل ضمن الفترة.</p><?php endif; ?></div></section>
    <section class="fin-panel"><header><div><span>Payment methods</span><h2>طرق القبض</h2></div></header><div class="fin-mini-list"><?php foreach($by_method as $row): ?><div><span><?=h($row['label'])?></span><b><?=number_format((float)$row['total'],2)?></b></div><?php endforeach; ?><?php if(!$by_method):?><p class="fin-empty">لا توجد بيانات.</p><?php endif;?></div></section>
    <section class="fin-panel"><header><div><span>Expense categories</span><h2>تصنيفات المصروفات</h2></div></header><div class="fin-mini-list is-expense"><?php foreach($by_category as $row): ?><div><span><?=h($row['label'])?></span><b><?=number_format((float)$row['total'],2)?></b></div><?php endforeach; ?><?php if(!$by_category):?><p class="fin-empty">لا توجد بيانات.</p><?php endif;?></div></section>
    <section class="fin-panel fin-panel--wide"><header><div><span>Last 14 days</span><h2>اتجاه الحركة اليومية</h2></div><a href="finance_day_report.php?day=<?=h(date('Y-m-d'))?>">تقرير اليوم</a></header><div class="fin-trend"><?php foreach($daily_recent as $row): ?><article><time><?=h(date('m/d',strtotime($row['day'])))?></time><div><i class="is-in" style="height:<?=max(2,$row['in']/$daily_max*72)?>px" title="مقبوضات <?=number_format($row['in'],2)?>"></i><i class="is-out" style="height:<?=max(2,$row['out']/$daily_max*72)?>px" title="مصروفات <?=number_format($row['out'],2)?>"></i></div><b class="<?=$row['net']<0?'is-negative':''?>"><?=number_format($row['net'],0)?></b></article><?php endforeach; ?></div><footer><span><i class="is-in"></i> المقبوضات</span><span><i class="is-out"></i> المصروفات</span></footer></section>
  </div>
</div></section></div>
<?php include __DIR__.'/footer.php'; ?>
