<?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
$booking_id = (int)($_GET['booking_id'] ?? 0);
if(!$booking_id){ die("booking_id required"); }

// account codes: AR 1210, cash handled in payments, revenue per invoice lines
$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"); }

// load booking + items
$st=$pdo->prepare("SELECT b.*, c.full_name customer_name FROM bookings b JOIN customers c ON c.id=b.customer_id WHERE b.id=? AND b.company_id=?");
$st->execute([$booking_id,$cid]); $b=$st->fetch(PDO::FETCH_ASSOC);
if(!$b){ die("Booking not found"); }

$it=$pdo->prepare("SELECT bi.*, s.name service_name, s.revenue_account_id, s.default_price FROM booking_items bi JOIN services s ON s.id=bi.service_id WHERE bi.booking_id=?");
$it->execute([$booking_id]); $items=$it->fetchAll(PDO::FETCH_ASSOC);

function next_no(PDO $pdo, int $cid, string $table, string $col, string $prefix): string {
  $st=$pdo->prepare("SELECT $col FROM $table WHERE company_id=? ORDER BY id DESC LIMIT 1");
  $st->execute([$cid]);
  $last=$st->fetchColumn();
  $n=1;
  if($last && preg_match('/(\d+)$/',$last,$m)) $n=(int)$m[1]+1;
  return $prefix . str_pad((string)$n, 5, '0', STR_PAD_LEFT);
}

$msg=$err=null;

if($_SERVER['REQUEST_METHOD']==='POST'){
  csrf_check();
  $date = $_POST['invoice_date'] ?? date('Y-m-d');
  try{
    $pdo->beginTransaction();
    $inv_no = next_no($pdo,$cid,'invoices','invoice_no','INV-');
    $pdo->prepare("INSERT INTO invoices (company_id, invoice_no, invoice_date, customer_id, booking_id, status, total, paid, notes)
                   VALUES (?,?,?,?,?,'ISSUED',0,0,?)")
        ->execute([$cid,$inv_no,$date,(int)$b['customer_id'],$booking_id,trim($_POST['notes'])]);
    $inv_id=(int)$pdo->lastInsertId();

    $total=0;
    $insLine=$pdo->prepare("INSERT INTO invoice_lines (invoice_id, description, revenue_account_id, qty, unit_price, line_total) VALUES (?,?,?,?,?,?)");
    foreach($items as $x){
      $qty=(float)$x['qty'];
      $price=(float)$x['unit_price'];
      if($price<=0) $price=(float)$x['default_price'];
      $line_total=round($qty*$price,2);
      $rev=(int)$x['revenue_account_id'];
      if(!$rev) throw new Exception("Service revenue account missing. Please set revenue account in Services.");
      $insLine->execute([$inv_id, $x['service_name'], $rev, $qty, $price, $line_total]);
      $total += $line_total;
    }
    $pdo->prepare("UPDATE invoices SET total=? WHERE id=? AND company_id=?")->execute([$total,$inv_id,$cid]);

    // Create financial event INVOICE (AR Dr / Revenue Cr per line)
    $pdo->prepare("INSERT INTO financial_events (company_id, event_date, event_type, ref_table, ref_id, memo, status)
                   VALUES (?,?,?,?,?,?,'DRAFT')")
        ->execute([$cid,$date,'INVOICE','invoices',$inv_id,"فاتورة $inv_no"]);
    $eid=(int)$pdo->lastInsertId();

    $pdo->prepare("INSERT INTO financial_event_lines (event_id, account_id, debit, credit) VALUES (?,?,?,?)")
        ->execute([$eid, $ar_id, $total, 0]);

    $revAgg = [];
    $ln=$pdo->prepare("SELECT revenue_account_id, line_total FROM invoice_lines WHERE invoice_id=?");
    $ln->execute([$inv_id]);
    while($r=$ln->fetch(PDO::FETCH_ASSOC)){
      $revAgg[(int)$r['revenue_account_id']] = ($revAgg[(int)$r['revenue_account_id']] ?? 0) + (float)$r['line_total'];
    }
    $insF=$pdo->prepare("INSERT INTO financial_event_lines (event_id, account_id, debit, credit) VALUES (?,?,0,?)");
    foreach($revAgg as $acc=>$amt){
      $insF->execute([$eid, (int)$acc, round($amt,2)]);
    }

    audit_log($pdo, [
      'company_id' => $cid,
      'user_id' => (int)($_SESSION['user_id'] ?? 0),
      'module' => 'tourism',
      'action' => 'CREATE_INVOICE',
      'entity_type' => 'invoice',
      'entity_id' => (string)$inv_id,
      'description' => audit_compose_description('إصدار فاتورة', [
        'رقم الفاتورة' => (string)$inv_no,
        'رقم الحجز' => (string)($b['booking_no'] ?? ''),
        'العميل' => (string)($b['customer_name'] ?? ''),
        'الإجمالي' => audit_money($total),
        'عدد البنود' => (string)count($items),
        'تاريخ الفاتورة' => (string)$date,
      ]),
    ]);
    $pdo->commit();
    header("Location: /tourism/invoices.php?msg=".urlencode("تم إصدار الفاتورة $inv_no (Draft accounting)"));
    exit;
  }catch(Throwable $e){
    if($pdo->inTransaction()) $pdo->rollBack();
    $err=$e->getMessage();
  }
}

render_layout('إصدار فاتورة','الحجوزات <span class="mx-1">/</span> إصدار فاتورة', function() use($b,$items,$err){ ?>
<div class="container-fluid mt-3">
  <div class="fw-bold fs-4">إصدار فاتورة من الحجز <?= h($b['booking_no']) ?></div>
  <div class="text-secondary small">العميل: <?= h($b['customer_name']) ?></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="invoice_date" class="form-control" value="<?= date('Y-m-d') ?>"></div>
        <div class="col-md-9"><label class="form-label">ملاحظات</label><input name="notes" class="form-control"></div>
      </div>

      <div class="table-responsive mt-3">
        <table class="table align-middle">
          <thead><tr class="text-secondary small"><th>الخدمة</th><th class="text-end">الكمية</th><th class="text-end">سعر</th><th class="text-end">الإجمالي</th></tr></thead>
          <tbody>
            <?php $sum=0; foreach($items as $x): $lt=(float)$x['qty']*(float)$x['unit_price']; $sum+=$lt; ?>
            <tr>
              <td><?= h($x['service_name']) ?></td>
              <td class="text-end"><?= nf($x['qty']) ?></td>
              <td class="text-end"><?= nf($x['unit_price']) ?></td>
              <td class="text-end fw-semibold"><?= nf($lt) ?></td>
            </tr>
            <?php endforeach; ?>
          </tbody>
        </table>
      </div>
      <div class="d-flex justify-content-between align-items-center">
        <div class="fw-bold">ملاحظة: القيد سيكون Draft ويتم ترحيله من صفحة الترحيل.</div>
        <button class="btn btn-dark"><i class="bi bi-check2-circle"></i> إصدار الفاتورة</button>
      </div>
    </form>
  </div>
</div>
<?php }); ?>
