<?php
declare(strict_types=1);

/**
 * modules/accounts/income/edit.php
 *
 * Edit a manual income entry (non-booking / non-rental).
 * Restricts editing to:
 *   - type = 'income'
 *   - booking_id IS NULL
 *   - rental_id  IS NULL
 *   - account_code in {'CHAUF_INCOME','RENTAL_INCOME'}
 *
 * Updates `transactions`:
 *   date, account_code, segment, amount, reference, notes
 */

/////////////////////////////////////////////////////////
// 1) Bootstrap & guards
/////////////////////////////////////////////////////////
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;

/////////////////////////////////////////////////////////
// 2) Allowed income accounts
/////////////////////////////////////////////////////////
$incomeAccounts = [
  'CHAUF_INCOME'  => 'Chauffeur Income',
  'RENTAL_INCOME' => 'Rental Income',
];

/////////////////////////////////////////////////////////
// 3) Load target transaction
/////////////////////////////////////////////////////////
$id = (int)($_GET['id'] ?? $_POST['id'] ?? 0);
if ($id <= 0) {
  redirect(url_modules('accounts/income/list.php'));
}

// Optional return URL
$returnUrl = (string)($_GET['return'] ?? $_POST['return'] ?? url_modules('accounts/income/list.php'));

$sel = db()->prepare("
  SELECT id, company_id, `date`, account_code, type, amount, booking_id, rental_id, notes, reference, segment
  FROM transactions
  WHERE id=:id AND company_id=:cid
  LIMIT 1
");
$sel->execute([':id'=>$id, ':cid'=>$cid]);
$tx = $sel->fetch();

if (!$tx) {
  $errors[] = 'Income entry not found.';
} else {
  // Ensure it’s a manual income
  $isManualIncome = (
    (string)$tx['type'] === 'income' &&
    $tx['booking_id'] === null &&
    $tx['rental_id']  === null &&
    array_key_exists((string)$tx['account_code'], $incomeAccounts)
  );

  if (!$isManualIncome) {
    redirect(url_modules('accounts/income/list.php'));
  }
}

/////////////////////////////////////////////////////////
// 4) Handle POST
/////////////////////////////////////////////////////////
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action']==='save' && $tx) {
  try {
    csrf_verify((string)($_POST['csrf'] ?? ''));

    $account   = (string)($_POST['account_code'] ?? '');
    $date      = (string)($_POST['date'] ?? '');
    $amountStr = trim((string)($_POST['amount'] ?? '0'));
    $reference = trim((string)($_POST['reference'] ?? ''));
    $notes     = trim((string)($_POST['notes'] ?? ''));

    if (!array_key_exists($account, $incomeAccounts)) {
      throw new RuntimeException('Please select a valid income category.');
    }
    if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $date)) {
      throw new RuntimeException('Date is invalid.');
    }

    $amount = (float)str_replace([',',' '], ['',''], $amountStr);
    if (!is_finite($amount) || $amount <= 0) {
      throw new RuntimeException('Amount must be a positive number.');
    }

    // ✅ Determine correct segment based on account
    $segment = null;
    if ($account === 'CHAUF_INCOME') {
      $segment = 'Chauffeur';
    } elseif ($account === 'RENTAL_INCOME') {
      $segment = 'Rent';
    }

    $upd = db()->prepare("
      UPDATE transactions
         SET `date`       = :d,
             account_code = :acc,
             segment      = :segment,
             amount       = :amt,
             reference    = :ref,
             notes        = :notes
       WHERE id = :id AND company_id = :cid
       LIMIT 1
    ");
    $upd->execute([
      ':d'       => $date,
      ':acc'     => $account,
      ':segment' => $segment,
      ':amt'     => $amount,
      ':ref'     => ($reference !== '' ? $reference : null),
      ':notes'   => ($notes !== '' ? $notes : null),
      ':id'      => $id,
      ':cid'     => $cid,
    ]);

    audit_log('income.manual.update', 'transactions', $id, [
      'account' => $account,
      'segment' => $segment,
      'date'    => $date,
      'amount'  => $amount,
      'ref'     => $reference,
    ]);

    $sel->execute([':id'=>$id, ':cid'=>$cid]);
    $tx = $sel->fetch();

    $notice = 'Income updated successfully.';

  } catch (Throwable $e) {
    $errors[] = (defined('APP_ENV') && APP_ENV === 'dev') ? $e->getMessage() : 'Unable to save income.';
  }
}

/////////////////////////////////////////////////////////
// 5) Prefill for form
/////////////////////////////////////////////////////////
$today = new DateTimeImmutable('today');
$valAccount = (string)($tx['account_code'] ?? 'CHAUF_INCOME');
if (!array_key_exists($valAccount, $incomeAccounts)) $valAccount = 'CHAUF_INCOME';

$valDate   = (string)($tx['date'] ?? $today->format('Y-m-d'));
$valAmount = (string)number_format((float)($tx['amount'] ?? 0), 2, '.', '');
$valRef    = (string)($tx['reference'] ?? '');
$valNotes  = (string)($tx['notes'] ?? '');

/////////////////////////////////////////////////////////
// 6) Render
/////////////////////////////////////////////////////////
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">Edit Manual Income</h1>
    <div class="text-muted">Update a non-booking / non-rental income entry.</div>
  </div>
  <div class="d-flex flex-wrap gap-2">
    <a class="btn btn-outline-secondary" href="<?= e($returnUrl) ?>">↩ Back</a>
    <a class="btn btn-outline-secondary" href="<?= e(url_modules('accounts/income/list.php')) ?>">🧾 Manual Income</a>
    <a class="btn btn-outline-secondary" href="<?= e(url_modules('accounts/index.php')) ?>">🏦 Accounts Dashboard</a>
  </div>
</div>

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

<?php if ($tx): ?>
<div class="row g-3">
  <div class="col-12 col-xl-7">
    <div class="card shadow-sm h-100">
      <div class="card-body">
        <h2 class="h6 text-uppercase text-muted mb-3">Income Details</h2>
        <form method="post" class="row g-3">
          <input type="hidden" name="csrf" value="<?= e(csrf_token()) ?>">
          <input type="hidden" name="action" value="save">
          <input type="hidden" name="id" value="<?= (int)$id ?>">
          <input type="hidden" name="return" value="<?= e($returnUrl) ?>">

          <div class="col-md-6">
            <label class="form-label">Income Category</label>
            <select class="form-select" name="account_code" required>
              <?php foreach ($incomeAccounts as $code => $label): ?>
                <option value="<?= e($code) ?>" <?= $code===$valAccount?'selected':'' ?>>
                  <?= e($label) ?>
                </option>
              <?php endforeach; ?>
            </select>
            <div class="form-text">Choose Chauffeur or Rental Income.</div>
          </div>

          <div class="col-md-3">
            <label class="form-label">Date</label>
            <input type="date" class="form-control" name="date" value="<?= e(substr($valDate,0,10)) ?>" required>
          </div>

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

          <div class="col-md-6">
            <label class="form-label">Reference</label>
            <input class="form-control" name="reference" value="<?= e($valRef) ?>" placeholder="Receipt / Invoice #">
          </div>

          <div class="col-md-6">
            <label class="form-label">Notes (optional)</label>
            <input class="form-control" name="notes" value="<?= e($valNotes) ?>" placeholder="Short description">
          </div>

          <div class="col-12 d-flex gap-2">
            <button class="btn btn-dark">Save Changes</button>
            <a class="btn btn-outline-secondary" href="<?= e($returnUrl) ?>">Cancel</a>
          </div>
        </form>
      </div>
    </div>
  </div>

  <!-- Info card -->
  <div class="col-12 col-xl-5">
    <div class="card shadow-sm h-100">
      <div class="card-body">
        <h2 class="h6 text-uppercase text-muted mb-3">Entry Info</h2>
        <dl class="row mb-0">
          <dt class="col-4">ID</dt><dd class="col-8"><?= (int)$tx['id'] ?></dd>
          <dt class="col-4">Type</dt><dd class="col-8"><span class="badge text-bg-success">Income</span></dd>
          <dt class="col-4">Linked</dt><dd class="col-8">Manual (no booking/rental)</dd>
        </dl>
        <div class="text-muted small mt-2">
          For booking or rental invoices, income is posted automatically and cannot be edited here.
        </div>
      </div>
    </div>
  </div>
</div>
<?php endif; ?>

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