<?php
declare(strict_types=1);

/**
 * modules/partners/add.php
 *
 * Create a Partner (agent / affiliate / company that sends bookings).
 *
 * Parts:
 *  1) Bootstrap & guards
 *  2) Handle POST (validate & insert)
 *  3) Render form (with small UX helpers)
 */

////////////////////////////////////////////////////////////////
// 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;

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

    // Collect & trim inputs
    $name             = trim((string)($_POST['name'] ?? ''));
    $contact_name     = trim((string)($_POST['contact_name'] ?? ''));
    $phone            = trim((string)($_POST['phone'] ?? ''));
    $email            = trim((string)($_POST['email'] ?? ''));
    $address          = trim((string)($_POST['address'] ?? ''));
    $commission_type  = (string)($_POST['commission_type'] ?? 'fixed');
    $commission_value = (string)($_POST['commission_value'] ?? '0');
    $bank_details     = trim((string)($_POST['bank_details'] ?? ''));
    $notes            = trim((string)($_POST['notes'] ?? ''));

    // Validation
    if ($name === '') {
      $errors[] = 'Partner name is required.';
    }
    if (!in_array($commission_type, ['fixed','percent'], true)) {
      $commission_type = 'fixed';
    }

    // Numeric checks
    $commission_value = (float)preg_replace('/[^0-9.\-]/', '', $commission_value);
    if ($commission_value < 0) $commission_value = 0.00;
    if ($commission_type === 'percent' && $commission_value > 100) {
      $errors[] = 'Percentage commission cannot exceed 100%.';
    }

    // Simple email format check (optional)
    if ($email !== '' && !filter_var($email, FILTER_VALIDATE_EMAIL)) {
      $errors[] = 'Please enter a valid email address.';
    }

    // Optional: warn on duplicate name in same company
    if (!$errors) {
      $dup = db()->prepare("SELECT id FROM partners WHERE company_id=:cid AND name=:n LIMIT 1");
      $dup->execute([':cid'=>$cid, ':n'=>$name]);
      if ($dup->fetch()) {
        $errors[] = 'A partner with this name already exists.';
      }
    }

    // Insert
    if (!$errors) {
      $ins = db()->prepare("
        INSERT INTO partners
          (company_id, name, contact_name, phone, email, address,
           commission_type, commission_value, bank_details, notes, created_at, updated_at)
        VALUES
          (:cid, :name, :contact, :phone, :email, :address,
           :ctype, :cval, :bank, :notes, NOW(), NOW())
      ");
      $ins->execute([
        ':cid'    => $cid,
        ':name'   => $name,
        ':contact'=> $contact_name !== '' ? $contact_name : null,
        ':phone'  => $phone !== '' ? $phone : null,
        ':email'  => $email !== '' ? $email : null,
        ':address'=> $address !== '' ? $address : null,
        ':ctype'  => $commission_type,
        ':cval'   => $commission_value,
        ':bank'   => $bank_details !== '' ? $bank_details : null,
        ':notes'  => $notes !== '' ? $notes : null,
      ]);
      $pid = (int)db()->lastInsertId();

      audit_log('partner.create', 'partner', $pid, [
        'name' => $name,
        'commission' => [$commission_type, $commission_value]
      ]);

      // Redirect to list or edit page
      redirect(url_modules('partners/list.php') . '?added=1');
    }
  } catch (Throwable $e) {
    $errors[] = (defined('APP_ENV') && APP_ENV === 'dev') ? $e->getMessage() : 'Unable to save partner.';
  }
}

////////////////////////////////////////////////////////////////
// 3) Render form
////////////////////////////////////////////////////////////////
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 Partner</h1>
  <div class="d-flex gap-2">
    <a href="<?= e(url_modules('partners/list.php')) ?>" class="btn btn-outline-secondary">Back to Partners</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; ?>

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

  <!-- Sticky 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 new partner / affiliate</div>
      <div class="d-flex gap-2">
        <button type="submit" class="btn btn-dark">Save Partner</button>
        <a class="btn btn-outline-secondary" href="<?= e(url_modules('partners/list.php')) ?>">Cancel</a>
      </div>
    </div>
  </div>

  <div class="row g-3">
    <!-- Profile -->
    <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">Profile</h2>
          <div class="row g-3">
            <div class="col-md-8">
              <label class="form-label">Company / Partner Name <span class="text-danger">*</span></label>
              <input class="form-control" name="name" required value="<?= e($_POST['name'] ?? '') ?>">
            </div>
            <div class="col-md-4">
              <label class="form-label">Contact Person</label>
              <input class="form-control" name="contact_name" value="<?= e($_POST['contact_name'] ?? '') ?>">
            </div>

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

          <hr class="my-3">

          <h2 class="h6 text-uppercase text-muted mb-3">Commission</h2>
          <div class="row g-3 align-items-end">
            <div class="col-md-4">
              <label class="form-label">Type</label>
              <?php $ctype = $_POST['commission_type'] ?? 'fixed'; ?>
              <select class="form-select" name="commission_type" id="commission_type">
                <option value="fixed"   <?= $ctype==='fixed'?'selected':'' ?>>Fixed amount per booking</option>
                <option value="percent" <?= $ctype==='percent'?'selected':'' ?>>Percentage of booking</option>
              </select>
            </div>
            <div class="col-md-4">
              <label class="form-label" id="lbl_commission_value">
                <?= $ctype==='percent' ? 'Commission (%)' : 'Commission (£)' ?>
              </label>
              <div class="input-group">
                <span class="input-group-text" id="sym_commission"><?= $ctype==='percent' ? '%' : '£' ?></span>
                <input type="number" step="0.01" min="0" class="form-control" name="commission_value"
                       id="commission_value" value="<?= e($_POST['commission_value'] ?? '0.00') ?>">
              </div>
              <div class="form-text" id="help_commission">
                <?= $ctype==='percent' ? '0–100 allowed.' : 'Enter a fixed amount charged per booking.' ?>
              </div>
            </div>
            <div class="col-md-4">
              <div class="p-2 border rounded bg-light">
                <div class="small text-muted">Preview</div>
                <div class="fw-bold" id="commission_preview">—</div>
              </div>
            </div>
          </div>

          <hr class="my-3">

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

    <!-- Bank Info -->
    <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">Bank Details (Optional)</h2>
          <textarea class="form-control" name="bank_details" rows="8"
            placeholder="Account name, number, sort code, IBAN, etc."><?= e($_POST['bank_details'] ?? '') ?></textarea>

          <div class="alert alert-info mt-3 mb-0 small">
            Bank details are stored for reference and payouts. They are <strong>not</strong> shared with clients.
          </div>
        </div>
      </div>
    </div>
  </div>

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

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

<script>
(function(){
  const $type   = document.getElementById('commission_type');
  const $value  = document.getElementById('commission_value');
  const $lbl    = document.getElementById('lbl_commission_value');
  const $sym    = document.getElementById('sym_commission');
  const $help   = document.getElementById('help_commission');
  const $prev   = document.getElementById('commission_preview');

  function format(n){ const x = parseFloat(n); return isNaN(x)?'0.00':x.toFixed(2); }

  function refreshUI(){
    const t = $type.value;
    if (t === 'percent') {
      $lbl.textContent = 'Commission (%)';
      $sym.textContent = '%';
      $help.textContent = '0–100 allowed.';
      if (parseFloat($value.value) > 100) $value.value = '100';
    } else {
      $lbl.textContent = 'Commission (£)';
      $sym.textContent = '£';
      $help.textContent = 'Enter a fixed amount charged per booking.';
    }
    // Tiny preview
    const v = parseFloat($value.value || '0');
    $prev.textContent = (t === 'percent')
      ? (format(v) + '% of client price')
      : ('£' + format(v) + ' per booking');
  }

  $type.addEventListener('change', refreshUI);
  $value.addEventListener('input', refreshUI);
  refreshUI();
})();
</script>
