<?php
declare(strict_types=1);

/**
 * modules/partners/edit.php
 *
 * Edit a Partner (agent / affiliate / company that sends bookings).
 *
 * Parts:
 *  1) Bootstrap & guards
 *  2) Fetch partner
 *  3) Handle POST (validate & update; dynamic columns)
 *  4) Render form (prefilled)
 */

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

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

$errors = [];
$notice = null;

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

////////////////////////////////////////////////////////////////
// 3) Handle POST (validate & update; dynamic columns)
////////////////////////////////////////////////////////////////
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  try {
    csrf_verify((string)($_POST['csrf'] ?? ''));

    $name   = trim((string)($_POST['name'] ?? ''));
    $cname  = trim((string)($_POST['contact_name'] ?? ''));
    $phone  = trim((string)($_POST['phone'] ?? ''));
    $email  = trim((string)($_POST['email'] ?? ''));
    $addr   = trim((string)($_POST['address'] ?? ''));
    $ctype  = (string)($_POST['commission_type'] ?? 'fixed');
    $cval   = (float)($_POST['commission_value'] ?? 0);
    $bank   = trim((string)($_POST['bank_details'] ?? ''));
    $notes  = trim((string)($_POST['notes'] ?? ''));

    if ($name === '') {
      $errors[] = 'Partner name is required.';
    }
    if (!in_array($ctype, ['fixed','percent'], true)) {
      $ctype = 'fixed';
    }
    if ($ctype === 'percent' && ($cval < 0 || $cval > 100)) {
      $errors[] = 'Percentage commission must be between 0 and 100.';
    }
    if ($email !== '' && !filter_var($email, FILTER_VALIDATE_EMAIL)) {
      $errors[] = 'Invalid email address.';
    }

    // Detect optional columns to avoid "Unknown column" errors
    $colExists = ['address'=>false, 'bank_details'=>false, 'updated_at'=>false];
    try {
      $chk = db()->prepare("
        SELECT COLUMN_NAME
          FROM INFORMATION_SCHEMA.COLUMNS
         WHERE TABLE_SCHEMA = DATABASE()
           AND TABLE_NAME = 'partners'
      ");
      $chk->execute();
      while ($col = $chk->fetchColumn()) {
        if (array_key_exists($col, $colExists)) $colExists[$col] = true;
      }
    } catch (Throwable $e) {
      // Fallback: conservative (assume these optional columns may not exist)
      $colExists = ['address'=>false, 'bank_details'=>false, 'updated_at'=>false];
    }

    if (!$errors) {
      $set = [
        "name = :name",
        "contact_name = :cname",
        "phone = :phone",
        "email = :email",
        "commission_type = :ctype",
        "commission_value = :cval",
        "notes = :notes"
      ];
      $args = [
        ':name'  => $name,
        ':cname' => ($cname !== '' ? $cname : null),
        ':phone' => ($phone !== '' ? $phone : null),
        ':email' => ($email !== '' ? $email : null),
        ':ctype' => $ctype,
        ':cval'  => $cval,
        ':notes' => ($notes !== '' ? $notes : null),
        ':id'    => $pid,
        ':cid'   => $cid,
      ];

      if ($colExists['address']) {
        $set[]        = "address = :addr";
        $args[':addr']= ($addr !== '' ? $addr : null);
      }
      if ($colExists['bank_details']) {
        $set[]          = "bank_details = :bank";
        $args[':bank']  = ($bank !== '' ? $bank : null);
      }
      if ($colExists['updated_at']) {
        $set[] = "updated_at = NOW()";
      }

      $sql = "UPDATE partners SET ".implode(', ', $set)." WHERE id = :id AND company_id = :cid LIMIT 1";
      $upd = db()->prepare($sql);
      $upd->execute($args);

      audit_log('partner.update', 'partner', $pid, ['fields'=>'profile']);

      // Reload for fresh display
      $sel->execute([':id' => $pid, ':cid' => $cid]);
      $partner = $sel->fetch();

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

////////////////////////////////////////////////////////////////
// 4) 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">Edit 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()) ?>">
  <input type="hidden" name="id" value="<?= (int)$pid ?>">

  <!-- 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">Update partner details & commission</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('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'] ?? $partner['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'] ?? $partner['contact_name'] ?? '') ?>">
            </div>

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

          <hr class="my-3">

          <h2 class="h6 text-uppercase text-muted mb-3">Commission</h2>
          <?php $ctypeCur = $_POST['commission_type'] ?? ($partner['commission_type'] ?? 'fixed'); ?>
          <div class="row g-3 align-items-end">
            <div class="col-md-4">
              <label class="form-label">Type</label>
              <select class="form-select" name="commission_type" id="commission_type">
                <option value="fixed"   <?= $ctypeCur==='fixed'?'selected':'' ?>>Fixed amount per booking</option>
                <option value="percent" <?= $ctypeCur==='percent'?'selected':'' ?>>Percentage of booking</option>
              </select>
            </div>
            <div class="col-md-4">
              <label class="form-label" id="lbl_commission_value">
                <?= $ctypeCur==='percent' ? 'Commission (%)' : 'Commission (£)' ?>
              </label>
              <div class="input-group">
                <span class="input-group-text" id="sym_commission"><?= $ctypeCur==='percent' ? '%' : '£' ?></span>
                <input type="number" step="0.01" min="0" class="form-control" name="commission_value"
                       id="commission_value"
                       value="<?= e($_POST['commission_value'] ?? (string)($partner['commission_value'] ?? '0.00')) ?>">
              </div>
              <div class="form-text" id="help_commission">
                <?= $ctypeCur==='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'] ?? $partner['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'] ?? $partner['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 Changes</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 fmt(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.';
    }
    const v = parseFloat($value.value || '0');
    $prev.textContent = (t === 'percent')
      ? (fmt(v) + '% of client price')
      : ('£' + fmt(v) + ' per booking');
  }

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