<?php
require_once __DIR__ . '/../app/init.php';
require_once __DIR__ . '/../app/layout.php';
require_once __DIR__ . '/../app/audit.php';
require_login();
$pdo = db();
$cid = (int)$_SESSION['company_id'];
csrf_bootstrap();
?>
<?php
$invoice_id=(int)($_GET['invoice_id']??0);
if(!$invoice_id) die("invoice_id required");

// cash accounts
$cash=$pdo->prepare("SELECT id, code, name FROM accounts WHERE company_id=? AND is_cash=1 AND is_active=1 ORDER BY code");
$cash->execute([$cid]); $cashAcc=$cash->fetchAll(PDO::FETCH_ASSOC);
if(!$cashAcc) die("No cash accounts marked is_cash=1. Please mark خزنة/بنك.");

// AR account 1210
$ar = $pdo->prepare("SELECT id FROM accounts WHERE company_id=? AND code='1210' LIMIT 1");
$ar->execute([$cid]); $ar_id=(int)($ar->fetchColumn()?:0);
if(!$ar_id) die("Missing AR account code 1210");

$inv=$pdo->prepare("SELECT i.*, c.full_name customer_name FROM invoices i JOIN customers c ON c.id=i.customer_id WHERE i.id=? AND i.company_id=?");
$inv->execute([$invoice_id,$cid]); $i=$inv->fetch(PDO::FETCH_ASSOC);
if(!$i) die("Invoice not found");
$due = max(0, (float)$i['total'] - (float)$i['paid']);

$msg=$err=null;
if($_SERVER['REQUEST_METHOD']==='POST'){
  csrf_check();
  try{
    $pdo->beginTransaction();
    $amount=(float)$_POST['amount'];
    if($amount<=0) throw new Exception("Amount must be > 0");
    $pay_date=$_POST['pay_date'] ?? date('Y-m-d');
    $cash_id=(int)$_POST['cash_account_id'];

    $pdo->prepare("INSERT INTO payments (company_id, invoice_id, pay_date, cash_account_id, amount, notes) VALUES (?,?,?,?,?,?)")
        ->execute([$cid,$invoice_id,$pay_date,$cash_id,$amount,trim($_POST['notes'])]);
    $pid=(int)$pdo->lastInsertId();

    // financial event PAYMENT: Cash Dr / AR Cr
    $pdo->prepare("INSERT INTO financial_events (company_id, event_date, event_type, ref_table, ref_id, memo, status)
                   VALUES (?,?,?,?,?,?,'DRAFT')")
        ->execute([$cid,$pay_date,'PAYMENT','payments',$pid,"تحصيل فاتورة ".$i['invoice_no']]);
    $eid=(int)$pdo->lastInsertId();
    $pdo->prepare("INSERT INTO financial_event_lines (event_id, account_id, debit, credit) VALUES (?,?,?,?)")
        ->execute([$eid,$cash_id,$amount,0]);
    $pdo->prepare("INSERT INTO financial_event_lines (event_id, account_id, debit, credit) VALUES (?,?,?,?)")
        ->execute([$eid,$ar_id,0,$amount]);

    $pdo->prepare("UPDATE invoices SET paid = paid + ? WHERE id=? AND company_id=?")->execute([$amount,$invoice_id,$cid]);
    audit_log($pdo, [
      'company_id' => $cid,
      'user_id' => (int)($_SESSION['user_id'] ?? 0),
      'module' => 'tourism',
      'action' => 'CREATE_PAYMENT',
      'entity_type' => 'payment',
      'entity_id' => (string)$pid,
      'description' => audit_compose_description('تسجيل تحصيل فاتورة', [
        'رقم الفاتورة' => (string)$i['invoice_no'],
        'العميل' => (string)$i['customer_name'],
        'المبلغ' => audit_money($amount),
        'طريقة المعالجة' => 'تحصيل',
        'الخزنة/البنك' => audit_account_label($pdo, $cid, $cash_id),
        'التاريخ' => (string)$pay_date,
        'المتبقي قبل التحصيل' => audit_money($due),
      ]),
    ]);
    $pdo->commit();
    header("Location: /tourism/invoices.php?msg=".urlencode("تم تسجيل التحصيل (Draft accounting)"));
    exit;
  }catch(Throwable $e){
    if($pdo->inTransaction()) $pdo->rollBack();
    $err=$e->getMessage();
  }
}

render_layout('تحصيل','الفواتير <span class="mx-1">/</span> تحصيل', function() use($i,$due,$cashAcc,$err){ ?>
<div class="container-fluid mt-3">
  <div class="fw-bold fs-4">تحصيل فاتورة <?= h($i['invoice_no']) ?></div>
  <div class="text-secondary small">العميل: <?= h($i['customer_name']) ?> — المتبقي: <?= nf($due) ?></div>

  <?php if($err): ?><div class="alert alert-danger mt-3"><?= h($err) ?></div><?php endif; ?>

  <div class="card cardx mt-3 p-3">
    <form method="post">
      <?= csrf_field() ?>
      <div class="row g-2">
        <div class="col-md-3"><label class="form-label">تاريخ التحصيل</label><input type="date" name="pay_date" class="form-control" value="<?= date('Y-m-d') ?>"></div>
        <div class="col-md-5"><label class="form-label">الخزنة/البنك</label>
          <div class="picker-with-action"><select id="pay_cash_account_id" name="cash_account_id" class="form-select selectpicker" data-live-search="true" required>
            <?php foreach($cashAcc as $a): ?><option value="<?= (int)$a['id'] ?>"><?= h($a['code'].' - '.$a['name']) ?></option><?php endforeach; ?>
          </select><button type="button" class="btn btn-outline-dark picker-action-btn js-open-ajax-modal" data-entity="account" data-target="#pay_cash_account_id" title="إضافة حساب جديد"><i class="bi bi-plus-lg"></i></button></div>
        </div>
        <div class="col-md-4"><label class="form-label">المبلغ</label><input type="number" step="0.01" name="amount" class="form-control" value="<?= h($due) ?>"></div>
        <div class="col-12"><label class="form-label">ملاحظات</label><input name="notes" class="form-control"></div>
      </div>
      <div class="mt-3 d-flex justify-content-end"><button class="btn btn-dark"><i class="bi bi-check2-circle"></i> حفظ التحصيل</button></div>
    </form>
  </div>
</div>
<script>
window.quickSources = window.quickSources || {};
window.quickSources.accounts_optional = [{value:'', text:'— بدون —'}, <?php foreach($cashAcc as $a): ?>{value:'<?= (int)$a['id'] ?>', text:'<?= h($a['code'].' - '.$a['name']) ?>'},<?php endforeach; ?>];
window.quickSources.revenue_accounts = [];
</script>
<?php }); ?>
