<?php
declare(strict_types=1);

/**
 * modules/accounts/income/add.php
 *
 * Add a manual income entry (non-booking / non-rental).
 * Choice limited to:
 *  - Chauffeur Income  (account_code = CHAUF_INCOME)
 *  - Rental Income     (account_code = RENTAL_INCOME)
 *
 * Inserts a row into `transactions`:
 *   company_id, date, account_code, segment, type='income', amount, booking_id=NULL, rental_id=NULL, notes, reference
 */

/////////////////////////////////////////////////////////
// 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) Prefill defaults
/////////////////////////////////////////////////////////
$today = new DateTimeImmutable('today');
$prefAccount = (string)($_GET['account'] ?? 'CHAUF_INCOME');
if (!array_key_exists($prefAccount, $incomeAccounts)) $prefAccount = 'CHAUF_INCOME';

/////////////////////////////////////////////////////////
// 4) Handle POST
/////////////////////////////////////////////////////////
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  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.');
    }

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

    // Determine segment (matches transactions.segment enum)
    $segment = ($account === 'CHAUF_INCOME') ? 'Chauffeur' : 'Rent';

    // Insert manual income
    $ins = db()->prepare("
      INSERT INTO transactions
        (company_id, `date`, account_code, segment, type, amount, booking_id, rental_id, notes, reference, created_at)
      VALUES
        (:cid, :d, :acc, :segment, 'income', :amt, NULL, NULL, :notes, :ref, NOW())
    ");
    $ins->execute([
      ':cid'     => $cid,
      ':d'       => $date,
      ':acc'     => $account,
      ':segment' => $segment,
      ':amt'     => $amount,
      ':notes'   => ($notes !== '' ? $notes : null),
      ':ref'     => ($reference !== '' ? $reference : null),
    ]);

    $newId = (int)db()->lastInsertId();
    audit_log('income.manual.create', 'transactions', $newId, [
      'account' => $account,
      'segment' => $segment,
      'date'    => $date,
      'amount'  => $amount,
      'ref'     => $reference,
    ]);

    // Redirect back to the manual income list using the SAME MONTH as the entered date
    $dateObj = new DateTimeImmutable($date);
    $mStart  = $dateObj->modify('first day of this month')->format('Y-m-d');
    $mEnd    = $dateObj->modify('last day of this month')->format('Y-m-d');

    $qs = http_build_query([
      'from' => $mStart,
      'to'   => $mEnd,
      'ok'   => 1,
    ]);
    redirect(url_modules('accounts/income/list.php') . '?' . $qs);

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

/////////////////////////////////////////////////////////
// 5) 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">Add Manual Income</h1>
    <div class="text-muted">Record income not linked to a specific booking or rental contract.</div>
  </div>
  <div class="d-flex flex-wrap gap-2">
    <a class="btn btn-outline-secondary" href="<?= e(url_modules('accounts/income/list.php')) ?>">↩ Back to 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; ?>

<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" autocomplete="off">
          <input type="hidden" name="csrf" value="<?= e(csrf_token()) ?>">

          <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===$prefAccount?'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($today->format('Y-m-d')) ?>" required>
          </div>

          <div class="col-md-3">
            <label class="form-label">Amount (£)</label>
            <input type="number" step="0.01" min="0.01" class="form-control" name="amount" placeholder="0.00" required>
          </div>

          <div class="col-md-6">
            <label class="form-label">Reference</label>
            <input class="form-control" name="reference" placeholder="Receipt / Invoice #">
          </div>

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

          <div class="col-12 d-flex gap-2">
            <button class="btn btn-dark">Save Income</button>
            <a class="btn btn-outline-secondary" href="<?= e(url_modules('accounts/income/list.php')) ?>">Cancel</a>
          </div>
        </form>
      </div>
    </div>
  </div>

  <!-- Helpful tips -->
  <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">Tips</h2>
        <ul class="mb-0">
          <li>Use <strong>Chauffeur Income</strong> for non-booking chauffeur sales (e.g., ad-hoc deposits).</li>
          <li>Use <strong>Rental Income</strong> for non-contract rental receipts.</li>
          <li>For booking or rental invoices, income is posted automatically by the system.</li>
        </ul>
      </div>
    </div>
  </div>
</div>

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