<?php
declare(strict_types=1);

/**
 * modules/corporates/edit.php
 *
 * Edit a Corporate Account (business customer).
 *
 * Parts:
 *  1) Bootstrap & guards
 *  2) Fetch corporate
 *  3) Handle POST (validate & update)
 *  4) 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'));

$id = (int)($_GET['id'] ?? $_POST['id'] ?? 0);
if ($id <= 0) redirect(url_modules('corporates/list.php'));

$errors = [];
$notice = null;

////////////////////////////////////////////////////////////////
// 2) Fetch corporate
////////////////////////////////////////////////////////////////
$sel = db()->prepare("
  SELECT *
    FROM corporates
   WHERE id = :id AND company_id = :cid
   LIMIT 1
");
$sel->execute([':id' => $id, ':cid' => $cid]);
$corp = $sel->fetch();
if (!$corp) redirect(url_modules('corporates/list.php'));

////////////////////////////////////////////////////////////////
// 3) Handle POST (validate & update)
////////////////////////////////////////////////////////////////
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'] ?? ''));

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

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

    if (!$errors) {
      $upd = db()->prepare("
        UPDATE corporates
           SET name = :name,
               contact_person = :contact_person,
               phone = :phone,
               email = :email,
               billing_address = :billing_address,
               credit_limit = :credit_limit,
               invoice_cycle = :invoice_cycle,
               payment_terms = :payment_terms,
               notes = :notes,
               updated_at = NOW()
         WHERE id = :id AND company_id = :cid
         LIMIT 1
      ");
      $upd->execute([
        ':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),
        ':id'              => $id,
        ':cid'             => $cid,
      ]);

      audit_log('corporate.update', 'corporate', $id, [
        'name' => $name, 'invoice_cycle' => $invoice_cycle, 'credit_limit' => $credit_limit_f
      ]);

      // Reload
      $sel->execute([':id' => $id, ':cid' => $cid]);
      $corp = $sel->fetch();
      $notice = 'Corporate account updated.';
    }
  } catch (Throwable $e) {
    $errors[] = (defined('APP_ENV') && APP_ENV === 'dev') ? $e->getMessage() : 'Unable to update corporate account.';
  }
}

////////////////////////////////////////////////////////////////
// 4) Render form (UX)
////////////////////////////////////////////////////////////////
include dirname(__DIR__, 2) . '/includes/header.php';

// Sticky values (POST first, then DB)
$val = function(string $key, string $fallback = '') use ($corp) {
  return $_POST[$key] ?? ($corp[$key] ?? $fallback);
};
?>
<div class="d-flex justify-content-between align-items-center mb-3">
  <h1 class="h4 mb-0">Edit 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()) ?>">
  <input type="hidden" name="id" value="<?= (int)$id ?>">

  <!-- 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">Update corporate details & billing preferences.</div>
      <div class="d-flex gap-2">
        <button type="submit" class="btn btn-dark">Save Changes</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($val('name')) ?>">
            </div>
            <div class="col-md-4">
              <label class="form-label">Contact Person</label>
              <input class="form-control" name="contact_person" value="<?= e($val('contact_person')) ?>">
            </div>

            <div class="col-md-4">
              <label class="form-label">Phone</label>
              <input class="form-control" name="phone" value="<?= e($val('phone')) ?>">
            </div>
            <div class="col-md-4">
              <label class="form-label">Email</label>
              <input type="email" class="form-control" name="email" value="<?= e($val('email')) ?>">
            </div>
            <div class="col-md-12">
              <label class="form-label">Billing Address</label>
              <textarea class="form-control" name="billing_address" rows="3"><?= e($val('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($val('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((string)($val('credit_limit', '0.00'))) ?>">
              </div>
              <div class="form-text">Optional. Leave 0.00 for no credit.</div>
            </div>
            <?php $cycle = $val('invoice_cycle','monthly'); ?>
            <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" <?= $cycle==='monthly'?'selected':''; ?>>Monthly</option>
                <option value="weekly"  <?= $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($val('payment_terms','30 days')) ?>">
              <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 <?= e($cycle) ?> • Terms: <?= e($val('payment_terms','30 days')) ?></div>
          </div>
        </div>
      </div>
    </div>
  </div>

  <div class="mt-3 d-flex gap-2">
    <button type="submit" class="btn btn-dark">Save Changes</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>
