<?php
require_once __DIR__ . '/../app/helpers.php';
require_once __DIR__ . '/../app/db.php';
require_once __DIR__ . '/../app/layout.php';
require_once __DIR__ . '/../app/Services/AccountingService.php';
require_login();

$pdo = db();
$cid = (int)$_SESSION['company_id'];
$uid = (int)$_SESSION['user_id'];

$cashAcc = $pdo->prepare("SELECT id, code, name FROM accounts WHERE company_id=? AND is_cash=1 AND is_active=1 ORDER BY code");
$cashAcc->execute([$cid]);
$cashAcc = $cashAcc->fetchAll();

$counterAcc = $pdo->prepare("SELECT id, code, name, type FROM accounts WHERE company_id=? AND is_active=1 ORDER BY code");
$counterAcc->execute([$cid]);
$counterAcc = $counterAcc->fetchAll();

$err = '';
if ($_SERVER['REQUEST_METHOD']==='POST') {
  csrf_check();
  $tx_date = $_POST['tx_date'] ?? date('Y-m-d');
  // لا يجوز إنشاء حركة بتاريخ أحدث من اليوم
  if ($tx_date > date('Y-m-d')) {
    $err = 'لا يجوز إنشاء حركة مالية في تاريخ أحدث من التاريخ الحالي';
  }
  $tx_type = $_POST['tx_type'] ?? 'IN';
  $cash_account_id = (int)($_POST['cash_account_id'] ?? 0);
  $counter_account_id = (int)($_POST['counter_account_id'] ?? 0);
  $amount = (float)($_POST['amount'] ?? 0);
  $memo = trim($_POST['memo'] ?? '');

  // Attachment upload (optional): images/pdf
  $attachment = null;
  if (!empty($_FILES['attachment']) && $_FILES['attachment']['error'] !== UPLOAD_ERR_NO_FILE) {
    if ($_FILES['attachment']['error'] !== UPLOAD_ERR_OK) {
      $err = 'تعذر رفع المرفق';
    } else {
      $maxBytes = 10 * 1024 * 1024; // 10 MB
      if ($_FILES['attachment']['size'] > $maxBytes) {
        $err = 'حجم المرفق كبير (الحد 10MB)';
      } else {
        $orig = $_FILES['attachment']['name'] ?? 'file';
        $ext = strtolower(pathinfo($orig, PATHINFO_EXTENSION));
        $allowed = ['jpg','jpeg','png','webp','pdf'];
        if (!in_array($ext, $allowed, true)) {
          $err = 'نوع المرفق غير مدعوم (PDF/صور فقط)';
        } else {
          $subdir = 'uploads/cash/' . date('Y') . '/' . date('m');
          $absDir = dirname(__DIR__) . '/' . $subdir;
          if (!is_dir($absDir)) { @mkdir($absDir, 0775, true); }
          $fname = 'tx_' . date('Ymd_His') . '_' . bin2hex(random_bytes(4)) . '.' . $ext;
          $absPath = $absDir . '/' . $fname;
          if (!move_uploaded_file($_FILES['attachment']['tmp_name'], $absPath)) {
            $err = 'تعذر حفظ المرفق على السيرفر';
          } else {
            $attachment = $subdir . '/' . $fname; // relative
          }
        }
      }
    }
  }

  if (!$err && (!$cash_account_id || !$counter_account_id || $amount<=0 || !in_array($tx_type,['IN','OUT'],true))) {
    $err = "تحقق من البيانات";
  } else {
    try{
      $svc = new AccountingService($pdo);
      $svc->createCashTxDraft([
        'company_id'=>$cid,
        'tx_date'=>$tx_date,
        'tx_type'=>$tx_type,
        'cash_account_id'=>$cash_account_id,
        'counter_account_id'=>$counter_account_id,
        'amount'=>$amount,
        'memo'=>$memo,
        'attachment'=>$attachment,
        'created_by'=>$uid
      ]);
      flash_set('تم إضافة الحركة المالية وترحيلها بنجاح');
      header("Location: " . url('/cash/index.php'));
      exit;
    } catch(Throwable $e){
      $err = "خطأ: " . $e->getMessage();
    }
  }
}

render_layout("إضافة حركة", "الرئيسية <span class='mx-1'>/</span> الحسابات <span class='mx-1'>/</span> الوارد والمنصرف <span class='mx-1'>/</span> إضافة", function() use ($cashAcc,$counterAcc,$err) {
?>
<div class="row g-3 mt-3">
  <div class="col-12 col-xl-8">
    <div class="card cardx p-3">
      <?php if($err): ?><div class="alert alert-danger"><?= h($err) ?></div><?php endif; ?>

      <form method="post" class="row g-3" enctype="multipart/form-data">
        <input type="hidden" name="_csrf" value="<?= h(csrf_token()) ?>">
        <div class="col-12 col-md-4">
          <label class="form-label">التاريخ</label>
          <?= render_date_input('tx_date', date('Y-m-d')) ?>
        </div>
        <div class="col-12 col-md-4">
          <label class="form-label">النوع</label>
          <select class="form-select selectpicker" data-live-search="true" name="tx_type">
            <option value="IN">وارد</option>
            <option value="OUT">منصرف</option>
          </select>
        </div>
        <div class="col-12 col-md-4">
          <label class="form-label">المبلغ</label>
          <input class="form-control" type="number" step="0.01" name="amount" required>
        </div>

        <div class="col-12 col-md-6">
          <label class="form-label">الحساب النقدي (صندوق/بنك)</label>
          <div class="picker-with-action"><select id="cash_account_id" class="selectpicker" data-style="form-select" data-live-search="true" data-size="8" required name="cash_account_id">
            <option value="">— اختر —</option>
            <?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="#cash_account_id" title="إضافة حساب جديد"><i class="bi bi-plus-lg"></i></button></div>
          <div class="text-secondary small mt-1">يتم الترحيل على حساب نقدي واحد لكل حركة.</div>
        </div>

        <div class="col-12 col-md-6">
          <label class="form-label">الحساب المقابل</label>
          <div class="picker-with-action"><select id="counter_account_id" class="selectpicker" data-style="form-select" data-live-search="true" data-size="8" required name="counter_account_id">
            <option value="">— اختر —</option>
            <?php foreach($counterAcc as $a): ?>
              <option value="<?= (int)$a['id'] ?>"><?= h($a['code'].' - '.$a['name'].' ('.$a['type'].')') ?></option>
            <?php endforeach; ?>
          </select><button type="button" class="btn btn-outline-dark picker-action-btn js-open-ajax-modal" data-entity="account" data-target="#counter_account_id" title="إضافة حساب جديد"><i class="bi bi-plus-lg"></i></button></div>
          <div class="text-secondary small mt-1">مثال: إيراد تأجير شقة / مصروف وقود / إلخ.</div>
        </div>

        <div class="col-12">
          <label class="form-label">ملاحظات</label>
          <input class="form-control" name="memo" placeholder="مثال: تحصيل حجز شقة فندقية...">
        </div>

        <div class="col-12">
          <label class="form-label">مرفق (اختياري)</label>
          <input class="form-control" type="file" name="attachment" accept=".pdf,image/*">
          <div class="text-secondary small mt-1">الملفات المدعومة: PDF / صور (حد أقصى 10MB).</div>
        </div>

        <div class="col-12 d-flex gap-2">
          <button class="btn btn-dark"><i class="bi bi-check2-circle"></i> حفظ وترحيل</button>
          <a class="btn btn-outline-secondary" href="<?= url('/cash/index.php') ?>">إلغاء</a>
        </div>
      </form>
    </div>
  </div>
</div>
<script>
window.quickSources = window.quickSources || {};
window.quickSources.accounts_optional = [{value:'', text:'— بدون —'}, <?php foreach($counterAcc as $a): ?>{value:'<?= (int)$a['id'] ?>', text:'<?= h($a['code'].' - '.$a['name']) ?>'},<?php endforeach; ?>];
window.quickSources.revenue_accounts = [<?php foreach($counterAcc as $a): if($a['type']!=='REVENUE') continue; ?>{value:'<?= (int)$a['id'] ?>', text:'<?= h($a['code'].' - '.$a['name']) ?>'},<?php endforeach; ?>];
</script>
<?php }); ?>