<?php
require_once dirname(__DIR__) . '/finance_bootstrap.php';
require_once dirname(__DIR__) . '/finance_daily_cashbox_lib.php';

function fdc_assert(bool $condition, string $message): void {
  if (!$condition) throw new RuntimeException($message);
  echo "PASS {$message}\n";
}

$day = '2098-07-14';
$conn->query("DELETE FROM cashbox_daily_accounts WHERE (day IN ('1998-07-14','2098-07-14') AND account_key='MAIN:main') OR account_key IN ('BRANCH:branch-test','AGENT:77')");
$conn->query("DELETE FROM payments WHERE DATE(COALESCE(paid_at,created_at)) IN ('1998-07-14','2098-07-14') AND collection_source_name IN ('النسخة الرئيسية','فرع تجريبي','مندوب تجريبي')");
$conn->query("DELETE FROM expenses WHERE COALESCE(spent_at,expense_date) IN ('1998-07-14','2098-07-14') AND note='test' AND category='test'");
$conn->begin_transaction();
try {
  $conn->query("DELETE FROM cashbox_daily_accounts WHERE day='{$day}'");
  $conn->query("INSERT INTO payments (amount,paid_at,created_at,payment_status,collection_source_type,collection_source_ref,collection_source_name,source_instance_id)
    VALUES (100,'{$day} 10:00:00','{$day} 10:00:00','POSTED','main','main','النسخة الرئيسية','main-test'),
           (60,'{$day} 11:00:00','{$day} 11:00:00','POSTED','branch','branch-test','فرع تجريبي','branch-test'),
           (40,'{$day} 12:00:00','{$day} 12:00:00','POSTED','agent','77','مندوب تجريبي','agent-test')");
  $conn->query("INSERT INTO expenses (title,category,amount,spent_at,expense_date,note,collection_source_type,collection_source_ref,collection_source_name,source_instance_id)
    VALUES ('test','test',10,'{$day}','{$day}','test','main','main','النسخة الرئيسية','main-test'),
           ('test','test',5,'{$day}','{$day}','test','branch','branch-test','فرع تجريبي','branch-test')");

  $live = finance_daily_view($conn, $day);
  $map = []; foreach ($live as $row) $map[$row['account_key']] = $row;
  fdc_assert(isset($map['MAIN:main'],$map['BRANCH:branch-test'],$map['AGENT:77']), 'فصل الصناديق إلى رئيسية وفرعية ومندوب');
  fdc_assert(abs(($map['MAIN:main']['income']-$map['MAIN:main']['expenses']) - 90.0) < 0.001, 'احتساب صافي اليومية للرئيسية');
  fdc_assert(abs(($map['BRANCH:branch-test']['income']-$map['BRANCH:branch-test']['expenses']) - 55.0) < 0.001, 'احتساب صافي اليومية للفرع');
  fdc_assert(abs(($map['AGENT:77']['income']-$map['AGENT:77']['expenses']) - 40.0) < 0.001, 'احتساب صافي اليومية للمندوب');
  $syntheticNet = $map['MAIN:main']['net'] + $map['BRANCH:branch-test']['net'] + $map['AGENT:77']['net'];
  fdc_assert(abs($syntheticNet - 185.0) < 0.001, 'احتساب صافي جميع النسخ');

  $closed = finance_daily_close_day($conn, $day, 'AUTO', 'test');
  fdc_assert(!empty($closed['ok']) && (int)$closed['closed'] >= 3, 'إغلاق جميع صناديق اليوم تلقائياً');
  $closedAgain = finance_daily_close_day($conn, $day, 'AUTO', 'test');
  fdc_assert((int)$closedAgain['closed'] === 0, 'منع تكرار الإغلاق اليومي');
  fdc_assert(finance_daily_account_closed($conn, $day, ['type'=>'branch','ref'=>'branch-test']), 'تمييز الصندوق المغلق حسب النسخة');
  $conn->rollback();
  $conn->query("DELETE FROM cashbox_daily_accounts WHERE (day IN ('1998-07-14','2098-07-14') AND account_key='MAIN:main') OR account_key IN ('BRANCH:branch-test','AGENT:77')");
  $conn->query("DELETE FROM payments WHERE DATE(COALESCE(paid_at,created_at)) IN ('1998-07-14','2098-07-14') AND collection_source_name IN ('النسخة الرئيسية','فرع تجريبي','مندوب تجريبي')");
  $conn->query("DELETE FROM expenses WHERE COALESCE(spent_at,expense_date) IN ('1998-07-14','2098-07-14') AND note='test' AND category='test'");
  echo "ALL DAILY CASHBOX TESTS PASSED\n";
} catch (Throwable $e) {
  $conn->rollback();
  fwrite(STDERR, "FAIL {$e->getMessage()}\n");
  exit(1);
}
