<?php
declare(strict_types=1);

require_once dirname(__DIR__, 3) . '/config/functions.php';
require_role(['Accounts','MD','Admin','Management']);

$user = current_user();
$cid  = (int)($user['company_id'] ?? 0);
if ($cid <= 0) redirect(url_public('login.php'));

$errors = [];
$notice = null;

// ------------------------------------------------------
// Helpers
// ------------------------------------------------------
function ensure_dir(string $dir): void {
  if (!is_dir($dir)) @mkdir($dir, 0775, true);
}

// ------------------------------------------------------
// Load accounts (COGS + Expenses)
// ------------------------------------------------------
$accountsByType = []; // ['Cost of Goods Sold'=>[], 'Operating Expenses'=>[]]
try {
  $st = db()->prepare("
    SELECT code, name, type
    FROM chart_of_accounts
    WHERE company_id = :cid
      AND type IN ('cogs','expense')
      AND (is_active = 1 OR is_active IS NULL)
    ORDER BY type ASC, name ASC
  ");
  $st->execute([':cid'=>$cid]);
  $rows = $st->fetchAll();

  foreach ($rows as $r) {
    $label = ($r['type']==='cogs') ? 'Cost of Goods Sold' : 'Operating Expenses';
    $accountsByType[$label][] = [
      'code' => $r['code'],
      'name' => $r['name'],
    ];
  }
} catch (Throwable $e) {
  $errors[] = 'Unable to load expense accounts.';
}

// ------------------------------------------------------
// Handle POST
// ------------------------------------------------------
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  try {
    csrf_verify((string)($_POST['csrf'] ?? ''));

    $date   = trim((string)($_POST['date'] ?? date('Y-m-d')));
    $segment= trim((string)($_POST['segment'] ?? ''));
    $acct   = trim((string)($_POST['account_code'] ?? ''));
    $amount = (float)($_POST['amount'] ?? 0);
    $ref    = trim((string)($_POST['reference'] ?? ''));
    $mile   = trim((string)($_POST['milestone'] ?? ''));
    $notes  = trim((string)($_POST['notes'] ?? ''));

    // Basic validation
    if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $date)) $errors[] = 'Invalid date.';
    if ($segment === '') $errors[] = 'Please select Rent or Chauffeur.';
    if ($acct === '') $errors[] = 'Please select an expense type.';
    if ($amount <= 0) $errors[] = 'Amount must be greater than zero.';

    // Verify account exists
    if ($acct !== '') {
      $chk = db()->prepare("
        SELECT 1 FROM chart_of_accounts
        WHERE company_id = :cid AND code = :code AND type IN ('cogs','expense')
        LIMIT 1
      ");
      $chk->execute([':cid'=>$cid, ':code'=>$acct]);
      if (!$chk->fetch()) $errors[] = 'Selected account not found.';
    }

    // Handle file upload
    $uploadedUrl = null;
    if (!empty($_FILES['file']['name'])) {
      if (!is_uploaded_file($_FILES['file']['tmp_name']) || $_FILES['file']['error'] !== UPLOAD_ERR_OK) {
        $errors[] = 'File upload failed.';
      } else {
        $ext = strtolower(pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION));
        $safe = 'exp_' . $cid . '_' . date('Ymd_His') . '_' . bin2hex(random_bytes(4)) . ($ext ? '.'.$ext : '');
        $dirAbs = dirname(__DIR__, 3) . '/public/uploads/expenses';
        ensure_dir($dirAbs);
        $destAbs = $dirAbs . '/' . $safe;
        if (!move_uploaded_file($_FILES['file']['tmp_name'], $destAbs)) {
          $errors[] = 'Could not move uploaded file.';
        } else {
          $uploadedUrl = 'uploads/expenses/' . $safe;
        }
      }
    }

    // ------------------------------------------------------
    // Save to DB
    // ------------------------------------------------------
    if (!$errors) {
      $cols = ['company_id','date','account_code','type','amount','segment'];
      $vals = [':cid',':dt',':acc',"'expense'",':amt',':seg'];
      $args = [
        ':cid'=>$cid,
        ':dt'=>$date,
        ':acc'=>$acct,
        ':amt'=>$amount,
        ':seg'=>$segment,
      ];

      if ($notes !== '') { $cols[]='notes'; $vals[]=':notes'; $args[':notes']=$notes; }
      if ($ref   !== '') { $cols[]='reference'; $vals[]=':ref'; $args[':ref']=$ref; }
      if ($mile  !== '') { $cols[]='milestone'; $vals[]=':mile'; $args[':mile']=$mile; }
      if ($uploadedUrl)  { $cols[]='attachment_url'; $vals[]=':file'; $args[':file']=$uploadedUrl; }

      $cols[]='created_at'; $vals[]='NOW()';

      $sql = "INSERT INTO transactions (".implode(',', $cols).") VALUES (".implode(',', $vals).")";
      $ins = db()->prepare($sql);
      $ins->execute($args);

      audit_log('expense.add','transaction',(int)db()->lastInsertId(),[
        'account'=>$acct,'amount'=>$amount,'date'=>$date,'ref'=>$ref,'segment'=>$segment
      ]);

      $mStart=(new DateTimeImmutable($date))->modify('first day of this month')->format('Y-m-d');
      $mEnd  =(new DateTimeImmutable($date))->modify('last day of this month')->format('Y-m-d');
      redirect(url_modules('accounts/expenses/list.php').'?from='.$mStart.'&to='.$mEnd.'&ok=1');
    }

  } catch (Throwable $e) {
    $errors[] = 'Unable to save expense. '.$e->getMessage();
  }
}

$defDate = date('Y-m-d');
include dirname(__DIR__, 3) . '/includes/header.php';
?>
<div class="d-flex justify-content-between align-items-center mb-3">
  <div>
    <h1 class="h4 mb-0">Add Expense</h1>
    <div class="text-muted">Select Rent/Chauffeur segment and expense type.</div>
  </div>
  <a class="btn btn-outline-secondary" href="<?= e(url_modules('accounts/expenses/list.php')) ?>">← Back</a>
</div>

<?php if ($errors): ?><div class="alert alert-danger"><ul><?php foreach($errors as $er) echo "<li>".e($er)."</li>";?></ul></div><?php endif; ?>

<form method="post" enctype="multipart/form-data" class="row g-3">
  <input type="hidden" name="csrf" value="<?= e(csrf_token()) ?>">

  <div class="col-md-6">
    <label class="form-label">Date</label>
    <input type="date" class="form-control" name="date" value="<?= e($_POST['date']??$defDate) ?>" required>
  </div>

  <div class="col-md-6">
    <label class="form-label">Amount (£)</label>
    <input type="number" step="0.01" min="0" class="form-control" name="amount"
           value="<?= e($_POST['amount']??'') ?>" required>
  </div>

  <div class="col-md-6">
    <label class="form-label">Business Segment</label>
    <select class="form-select" name="segment" required>
      <option value="">Select…</option>
      <option value="Rent" <?= (($_POST['segment']??'')==='Rent'?'selected':'') ?>>Rent</option>
      <option value="Chauffeur" <?= (($_POST['segment']??'')==='Chauffeur'?'selected':'') ?>>Chauffeur</option>
    </select>
  </div>

  <div class="col-md-6">
    <label class="form-label">Expense Type</label>
    <select class="form-select" name="account_code" required>
      <option value="">Select expense type…</option>
      <?php foreach($accountsByType as $cat=>$list): ?>
        <optgroup label="<?= e($cat) ?>">
          <?php foreach($list as $a): ?>
            <option value="<?= e($a['code']) ?>" <?= (($_POST['account_code']??'')===$a['code']?'selected':'') ?>>
              <?= e($a['name']) ?> (<?= e($a['code']) ?>)
            </option>
          <?php endforeach; ?>
        </optgroup>
      <?php endforeach; ?>
    </select>
  </div>

  <div class="col-md-6">
    <label class="form-label">Reference</label>
    <input class="form-control" name="reference" value="<?= e($_POST['reference']??'') ?>">
  </div>

  <div class="col-md-6">
    <label class="form-label">Miscellaneous</label>
    <input class="form-control" name="milestone" value="<?= e($_POST['milestone']??'') ?>">
  </div>

  <div class="col-12">
    <label class="form-label">Notes</label>
    <textarea class="form-control" name="notes" rows="3"><?= e($_POST['notes']??'') ?></textarea>
  </div>

  <div class="col-12">
    <label class="form-label">Attach File</label>
    <input type="file" class="form-control" name="file">
  </div>

  <div class="col-12">
    <button class="btn btn-dark">Save Expense</button>
    <a class="btn btn-outline-secondary" href="<?= e(url_modules('accounts/expenses/list.php')) ?>">Cancel</a>
  </div>
</form>

<?php include dirname(__DIR__, 3) . '/includes/footer.php'; ?>
