<?php
declare(strict_types=1);

/**
 * modules/corporates/add.php
 *
 * Create a Corporate Account (business customer).
 *
 * Parts:
 *  1) Bootstrap & guards
 *  2) Handle POST (validate & insert)
 *  3) Render form (UX with sticky action bar)
 */

////////////////////////////////////////////////////////////////
// 1) Bootstrap & guards
////////////////////////////////////////////////////////////////
require_once dirname(__DIR__, 2) . '/config/functions.php';
require_role(['Admin','Ops','sales']);

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

$errors = [];
$notice = null;

// Defaults for form
$defaults = [
  'name'           => '',
  'contact_person' => '',
  'phone'          => '',
  'email'          => '',
  'billing_address'=> '',
  'credit_limit'   => '0.00',
  'invoice_cycle'  => 'monthly',
  'payment_terms'  => '30 days',
  'notes'          => '',
];

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

    // Gather & sanitize
    $name           = trim((string)($_POST['name'] ?? ''));
    $contact_person = trim((string)($_POST['contact_person'] ?? ''));
    $phone          = trim((string)($_POST['phone'] ?? ''));
    $email          = trim((string)($_POST['email'] ?? ''));
    $billing_addr   = trim((string)($_POST['billing_address'] ?? ''));
    $credit_limit   = (string)($_POST['credit_limit'] ?? '0');
    $invoice_cycle  = (string)($_POST['invoice_cycle'] ?? 'monthly');
    $payment_terms  = trim((string)($_POST['payment_terms'] ?? '30 days'));
    $notes          = trim((string)($_POST['notes'] ?? ''));

    // Coerce numeric
    $credit_limit_f = (float)preg_replace('/[^0-9.\-]/', '', $credit_limit);

    // Validate
    if ($name === '') $errors[] = 'Company name is required.';
    if (!in_array($invoice_cycle, ['weekly','monthly'], true)) $invoice_cycle = 'monthly';
    if ($email !== '' && !filter_var($email, FILTER_VALIDATE_EMAIL)) $errors[] = 'Invalid email address.';

    // If OK, insert
    if (!$errors) {
      $ins = db()->prepare("
        INSERT INTO corporates
          (company_id, name, contact_person, phone, email, billing_address,
           credit_limit, invoice_cycle, payment_terms, notes, created_at, updated_at)
        VALUES
          (:cid, :name, :contact_person, :phone, :email, :billing_address,
           :credit_limit, :invoice_cycle, :payment_terms, :notes, NOW(), NOW())
      ");
      $ins->execute([
        ':cid'            => $cid,
        ':name'           => $name,
        ':contact_person' => ($contact_person !== '' ? $contact_person : null),
        ':phone'          => ($phone !== '' ? $phone : null),
        ':email'          => ($email !== '' ? $email : null),
        ':billing_address'=> ($billing_addr !== '' ? $billing_addr : null),
        ':credit_limit'   => $credit_limit_f,
        ':invoice_cycle'  => $invoice_cycle,
        ':payment_terms'  => ($payment_terms !== '' ? $payment_terms : null),
        ':notes'          => ($notes !== '' ? $notes : null),
      ]);
      $newId = (int)db()->lastInsertId();
      audit_log('corporate.create', 'corporate', $newId, [
        'name' => $name, 'invoice_cycle' => $invoice_cycle, 'credit_limit' => $credit_limit_f
      ]);
      redirect(url_modules('corporates/list.php') . '?added=1');
    } else {
      // keep sticky values
      $defaults = array_merge($defaults, [
        'name'           => $name,
        'contact_person' => $contact_person,
        'phone'          => $phone,
        'email'          => $email,
        'billing_address'=> $billing_addr,
        'credit_limit'   => (string)$credit_limit_f,
        'invoice_cycle'  => $invoice_cycle,
        'payment_terms'  => $payment_terms,
        'notes'          => $notes,
      ]);
    }
  } catch (Throwable $e) {
    $errors[] = (defined('APP_ENV') && APP_ENV === 'dev') ? $e->getMessage() : 'Unable to create corporate account.';
  }
}

////////////////////////////////////////////////////////////////
// 3) Render form (UX)
////////////////////////////////////////////////////////////////
include dirname(__DIR__, 2) . '/includes/header.php';
?>
<div class="d-flex justify-content-between align-items-center mb-3">
  <h1 class="h4 mb-0">Add Corporate Account</h1>
  <a href="<?= e(url_modules('corporates/list.php')) ?>" class="btn btn-outline-secondary">Back to List</a>
</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; ?>

<form method="post" id="corpForm" autocomplete="off">
  <input type="hidden" name="csrf" value="<?= e(csrf_token()) ?>">

  <!-- Sticky action bar -->
  <div class="position-sticky top-0 z-3 pb-2" style="background:#f8fafc;">
    <div class="d-flex justify-content-between align-items-center mb-2 pt-2">
      <div class="small text-muted">Create a corporate account to enable monthly invoicing.</div>
      <div class="d-flex gap-2">
        <button type="submit" class="btn btn-dark">Save</button>
        <a class="btn btn-outline-secondary" href="<?= e(url_modules('corporates/list.php')) ?>">Cancel</a>
      </div>
    </div>
  </div>

  <div class="row g-3">
    <!-- Corporate details -->
    <div class="col-12 col-lg-7">
      <div class="card shadow-sm h-100">
        <div class="card-body">
          <h2 class="h6 text-uppercase text-muted mb-3">Company Details</h2>
          <div class="row g-3">
            <div class="col-md-8">
              <label class="form-label">Company Name <span class="text-danger">*</span></label>
              <input class="form-control" name="name" required value="<?= e($defaults['name']) ?>">
            </div>
            <div class="col-md-4">
              <label class="form-label">Contact Person</label>
              <input class="form-control" name="contact_person" value="<?= e($defaults['contact_person']) ?>">
            </div>

            <div class="col-md-4">
              <label class="form-label">Phone</label>
              <input class="form-control" name="phone" value="<?= e($defaults['phone']) ?>">
            </div>
            <div class="col-md-4">
              <label class="form-label">Email</label>
              <input type="email" class="form-control" name="email" value="<?= e($defaults['email']) ?>">
            </div>
            <div class="col-md-12">
              <label class="form-label">Billing Address</label>
              <textarea class="form-control" name="billing_address" rows="3"><?= e($defaults['billing_address']) ?></textarea>
            </div>
          </div>

          <hr class="my-3">

          <h2 class="h6 text-uppercase text-muted mb-3">Notes</h2>
          <textarea class="form-control" name="notes" rows="3" placeholder="Internal notes (optional)"><?= e($defaults['notes']) ?></textarea>
        </div>
      </div>
    </div>

    <!-- Finance & billing -->
    <div class="col-12 col-lg-5">
      <div class="card shadow-sm h-100">
        <div class="card-body">
          <h2 class="h6 text-uppercase text-muted mb-3">Finance & Billing</h2>
          <div class="row g-3 align-items-end">
            <div class="col-md-6">
              <label class="form-label">Credit Limit (£)</label>
              <div class="input-group">
                <span class="input-group-text">£</span>
                <input type="number" step="0.01" min="0" class="form-control" name="credit_limit" value="<?= e($defaults['credit_limit']) ?>">
              </div>
              <div class="form-text">Optional. Leave 0.00 for no credit.</div>
            </div>
            <div class="col-md-6">
              <label class="form-label">Invoice Cycle</label>
              <select class="form-select" name="invoice_cycle" id="invoice_cycle">
                <option value="monthly" <?= $defaults['invoice_cycle']==='monthly'?'selected':''; ?>>Monthly</option>
                <option value="weekly"  <?= $defaults['invoice_cycle']==='weekly'?'selected':''; ?>>Weekly</option>
              </select>
            </div>
            <div class="col-md-12">
              <label class="form-label">Payment Terms</label>
              <input class="form-control" name="payment_terms" value="<?= e($defaults['payment_terms']) ?>">
              <div class="form-text">e.g., 30 days, Due on receipt, EOM+15, etc.</div>
            </div>
          </div>

          <div class="p-2 border rounded bg-light mt-3">
            <div class="small text-muted">Preview</div>
            <div class="fw-bold" id="cyclePreview">Invoice monthly • Terms: <?= e($defaults['payment_terms']) ?></div>
          </div>
        </div>
      </div>
    </div>
  </div>

  <div class="mt-3 d-flex gap-2">
    <button type="submit" class="btn btn-dark">Save</button>
    <a class="btn btn-outline-secondary" href="<?= e(url_modules('corporates/list.php')) ?>">Cancel</a>
  </div>
</form>

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

<script>
(function(){
  const cycle = document.getElementById('invoice_cycle');
  const terms = document.querySelector('input[name="payment_terms"]');
  const prev  = document.getElementById('cyclePreview');

  function refresh(){
    const c = cycle.value === 'weekly' ? 'weekly' : 'monthly';
    const t = terms.value || '30 days';
    prev.textContent = 'Invoice ' + c + ' • Terms: ' + t;
  }
  cycle.addEventListener('change', refresh);
  terms.addEventListener('input', refresh);
  refresh();
})();
</script>
