<?php
chdir(dirname(__DIR__));
require_once 'db_bootstrap.php';
$conn=ensure_db(true);
require_once 'finance_partners_lib.php';
finance_partners_migrate($conn);
$prefix='codex_partner_'.bin2hex(random_bytes(5));
function fp_assert(bool $ok,string $label): void {if(!$ok)throw new RuntimeException('FAIL '.$label);echo "PASS {$label}\n";}
try{
  $conn->begin_transaction();
  $a=finance_partner_save($conn,['name'=>$prefix.'_A','code'=>$prefix.'_A','ownership_percent'=>60,'is_active'=>1],0);
  $b=finance_partner_save($conn,['name'=>$prefix.'_B','code'=>$prefix.'_B','ownership_percent'=>40,'is_active'=>1],0);
  fp_assert(!empty($a['ok'])&&!empty($b['ok']),'إضافة شريكين بحصص مجموعها 100%');
  $alloc=finance_capital_allocations($conn,100000,'ALL',0);
  fp_assert(count($alloc)===2&&abs((float)$alloc[0]['amount']+(float)$alloc[1]['amount']-100000)<.001,'توزيع رأس المال دون فرق تقريبي');
  $posted=finance_record_capital_purchase($conn,987654321,100000,'ALL',0,0,'2098-01-15');
  fp_assert(!empty($posted['ok']),'ترحيل شراء رأسمالي لكل الشركاء');
  $again=finance_record_capital_purchase($conn,987654321,100000,'ALL',0,0,'2098-01-15');
  fp_assert(!empty($again['ok'])&&!empty($again['allocations']),'منع تكرار قيد الشراء بمفتاح ثابت');
  $ids=[(int)$a['id'],(int)$b['id']];$idList=implode(',',$ids);
  $rs=$conn->query("SELECT COUNT(*) c,COALESCE(SUM(amount),0) total FROM finance_partner_ledger WHERE partner_id IN ({$idList}) AND reference_type='PURCHASE' AND reference_id=987654321");$row=$rs->fetch_assoc();
  fp_assert((int)$row['c']===2&&abs((float)$row['total']-100000)<.001,'قيدان فقط بإجمالي قيمة الشراء');
  $bad=finance_partner_save($conn,['name'=>$prefix.'_C','code'=>$prefix.'_C','ownership_percent'=>1,'is_active'=>1],0);
  fp_assert(empty($bad['ok']),'رفض تجاوز مجموع الملكية 100%');
  $conn->rollback();

  // Full posted-period test uses an isolated future accounting month and removes every fixture afterwards.
  $month='2098-02';$monthCloseInserted=false;$partnerIds=[];
  try{
    $a=finance_partner_save($conn,['name'=>$prefix.'_PA','code'=>$prefix.'_PA','ownership_percent'=>60,'is_active'=>1],0);
    $b=finance_partner_save($conn,['name'=>$prefix.'_PB','code'=>$prefix.'_PB','ownership_percent'=>40,'is_active'=>1],0);
    $partnerIds=[(int)$a['id'],(int)$b['id']];
    $ref=$conn->real_escape_string($prefix);
    $conn->query("INSERT INTO payments(amount,reference,paid_at,payment_status,created_at) VALUES(1000,'{$ref}','2098-02-05 10:00:00','POSTED','2098-02-05 10:00:00')");
    $conn->query("INSERT INTO expenses(title,amount,spent_at,expense_date,reference,expense_status,created_at) VALUES('test',200,'2098-02-06','2098-02-06','{$ref}','POSTED','2098-02-06 10:00:00')");
    $conn->query("INSERT INTO shop_purchases(invoice_no,currency,total,paid,accounting_class,created_at) VALUES('{$ref}','SYP',100,100,'OPERATING','2098-02-07 10:00:00')");
    $conn->query("INSERT IGNORE INTO month_closings(year,month,closed_by) VALUES(2098,2,'test')");$monthCloseInserted=$conn->affected_rows>0;
    $post=finance_profit_post($conn,$month,0);fp_assert(!empty($post['ok'])&&abs((float)$post['snapshot']['net_profit']-700)<.001,'احتساب الربح بعد المصروفات والمشتريات وتثبيته');
    $periodId=(int)$post['period_id'];$rs=$conn->query("SELECT COUNT(*) c,COALESCE(SUM(allocated_amount),0) total FROM finance_profit_allocations WHERE period_id={$periodId}");$row=$rs->fetch_assoc();
    fp_assert((int)$row['c']===2&&abs((float)$row['total']-700)<.001,'توزيع كامل الربح حسب الحصص بلا فرق تقريبي');
    $duplicate=finance_profit_post($conn,$month,0);fp_assert(empty($duplicate['ok']),'منع تثبيت أرباح الشهر مرتين');
  }finally{
    $ids=array_filter(array_map('intval',$partnerIds));$idList=$ids?implode(',',$ids):'0';
    $rs=$conn->query("SELECT id FROM finance_profit_periods WHERE month_key='{$month}' LIMIT 1");$period=$rs&&($row=$rs->fetch_assoc())?(int)$row['id']:0;
    if($period>0){$conn->query("DELETE FROM finance_profit_allocations WHERE period_id={$period}");$conn->query("DELETE FROM finance_partner_ledger WHERE reference_type='PROFIT_PERIOD' AND reference_id={$period}");$conn->query("DELETE FROM finance_profit_periods WHERE id={$period}");}
    $conn->query("DELETE FROM finance_partner_ledger WHERE partner_id IN ({$idList})");$conn->query("DELETE FROM finance_partners WHERE id IN ({$idList})");
    $ref=$conn->real_escape_string($prefix);$conn->query("DELETE FROM payments WHERE reference='{$ref}'");$conn->query("DELETE FROM expenses WHERE reference='{$ref}'");$conn->query("DELETE FROM shop_purchases WHERE invoice_no='{$ref}'");
    if($monthCloseInserted)$conn->query("DELETE FROM month_closings WHERE year=2098 AND month=2 AND closed_by='test'");
  }
  echo "ALL PARTNERS ACCOUNTING TESTS PASSED\n";
}catch(Throwable $e){@$conn->rollback();fwrite(STDERR,$e->getMessage()."\n");exit(1);}
