<?php
session_start();
$active_nav = 'organization_edit';
include_once("config/db.php");
require_once __DIR__ . '/header.php';

if (!function_exists('csrf_token')) {
    function csrf_token(): string {
        if (empty($_SESSION['csrf_token'])) $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
        return $_SESSION['csrf_token'];
    }
    function csrf_verify(): bool {
        return !empty($_POST['csrf_token']) && !empty($_SESSION['csrf_token'])
            && hash_equals($_SESSION['csrf_token'], $_POST['csrf_token']);
    }
    function csrf_field(): string { return '<input type="hidden" name="csrf_token" value="'.htmlspecialchars(csrf_token()).'">'; }
}
// Previously trapped inside the csrf_token fallback above — guard individually
// so they exist even when includes/csrf.php provides the csrf helpers.
if (!function_exists('csrf_verify')) {
    function csrf_verify(): bool {
        return !empty($_POST['csrf_token']) && !empty($_SESSION['csrf_token'])
            && hash_equals($_SESSION['csrf_token'], $_POST['csrf_token']);
    }
}
if (!function_exists('h')) {
    function h(?string $v): string { return htmlspecialchars($v ?? '', ENT_QUOTES|ENT_SUBSTITUTE, 'UTF-8'); }
}

$org_id = (int)($_GET['id'] ?? 0);
if (!$org_id) { header("Location: organizations.php"); exit; }

// Load org
$s = $conn->prepare("SELECT * FROM organizations WHERE id=? LIMIT 1");
$s->bind_param("i", $org_id); $s->execute();
$org = $s->get_result()->fetch_assoc();
if (!$org) { header("Location: organizations.php"); exit; }

$page_title = 'Edit ' . htmlspecialchars($org['name']);
$success    = '';
$error      = '';

// ─── Handle POST ────────────────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!csrf_verify()) { $error = "Security token mismatch."; goto render; }

    $name           = trim($_POST['name']           ?? '');
    $type           = trim($_POST['type']           ?? '');
    $contact_person = trim($_POST['contact_person'] ?? '');
    $email          = trim($_POST['email']          ?? '');
    $phone          = trim($_POST['phone']          ?? '');
    $address        = trim($_POST['address']        ?? '');
    $status         = trim($_POST['status']         ?? '');

    if (!$name || !$type) { $error = "Name and type are required."; goto render; }
    if (!in_array($status, ['active','suspended','inactive'])) { $error = "Invalid status."; goto render; }
    if ($email && !filter_var($email, FILTER_VALIDATE_EMAIL)) { $error = "Invalid email address."; goto render; }

    $upd = $conn->prepare(
        "UPDATE organizations SET name=?, type=?, contact_person=?, email=?, phone=?, address=?, status=? WHERE id=?"
    );
    $upd->bind_param("sssssssi", $name, $type, $contact_person, $email, $phone, $address, $status, $org_id);

    if ($upd->execute()) {
        // If status changed to suspended, lock out org admins
        if ($status === 'suspended' && $org['status'] !== 'suspended') {
            $conn->query("UPDATE users SET status=0 WHERE organization_id={$org_id} AND role='org_admin'");
        } elseif ($status === 'active' && $org['status'] !== 'active') {
            $conn->query("UPDATE users SET status=1 WHERE organization_id={$org_id} AND role='org_admin'");
        }
        $org = array_merge($org, compact('name','type','contact_person','email','phone','address','status'));
        $success = "Organisation updated successfully.";
    } else {
        $error = "Update failed. Please try again.";
    }
}

render:
?>

<div class="anim-up">

<!-- Breadcrumb -->
<div style="font-size:.8rem;color:var(--text-muted);margin-bottom:20px">
  <a href="organizations.php" style="color:var(--primary);font-weight:600">Organisations</a>
  <span style="margin:0 8px">›</span>
  <a href="organization_view.php?id=<?php echo $org_id; ?>" style="color:var(--primary);font-weight:600"><?php echo h($org['name']); ?></a>
  <span style="margin:0 8px">›</span>
  <span>Edit</span>
</div>

<div style="max-width:700px">

  <div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:24px;flex-wrap:wrap;gap:12px">
    <div>
      <h2 style="font-size:1.4rem;font-weight:800;letter-spacing:-.03em">Edit Organisation</h2>
      <p style="font-size:.84rem;color:var(--text-muted);margin-top:3px"><?php echo h($org['name']); ?></p>
    </div>
    <a href="organization_view.php?id=<?php echo $org_id; ?>" class="btn btn-secondary btn-md">← Back to View</a>
  </div>

  <?php if ($success): ?>
  <div class="alert alert-success"><svg viewBox="0 0 24 24" stroke-width="2"><polyline points="20 6 9 17 4 12"/></svg>
    <?php echo $success; ?> <a href="organization_view.php?id=<?php echo $org_id; ?>" style="text-decoration:underline;font-weight:700">View Organisation →</a>
  </div>
  <?php endif; ?>
  <?php if ($error): ?>
  <div class="alert alert-error"><svg viewBox="0 0 24 24" stroke-width="2"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></svg><?php echo $error; ?></div>
  <?php endif; ?>

  <div class="card">
    <div class="card-header"><h3>Organisation Details</h3></div>
    <div class="card-body">
      <form method="POST">
        <?php echo csrf_field(); ?>

        <div style="display:grid;grid-template-columns:1fr 1fr;gap:16px">
          <div class="form-group" style="grid-column:1/-1">
            <label>Organisation Name <span style="color:var(--error)">*</span></label>
            <input type="text" name="name" class="form-control" value="<?php echo h($org['name']); ?>" required>
          </div>

          <div class="form-group">
            <label>Organisation Type <span style="color:var(--error)">*</span></label>
            <select name="type" class="form-control" required>
              <?php foreach (['hospital','school','company','government','ngo','other'] as $t): ?>
              <option value="<?php echo $t; ?>" <?php echo $org['type']===$t?'selected':''; ?>><?php echo ucfirst($t); ?></option>
              <?php endforeach; ?>
            </select>
          </div>

          <div class="form-group">
            <label>Status</label>
            <select name="status" class="form-control">
              <option value="active"    <?php echo $org['status']==='active'?'selected':''; ?>>Active</option>
              <option value="suspended" <?php echo $org['status']==='suspended'?'selected':''; ?>>Suspended</option>
              <option value="inactive"  <?php echo $org['status']==='inactive'?'selected':''; ?>>Inactive</option>
            </select>
            <p style="font-size:.72rem;color:var(--text-muted);margin-top:4px">Suspending will immediately lock out all org administrators.</p>
          </div>

          <div class="form-group">
            <label>Contact Person</label>
            <input type="text" name="contact_person" class="form-control" value="<?php echo h($org['contact_person'] ?? ''); ?>">
          </div>

          <div class="form-group">
            <label>Organisation Email</label>
            <input type="email" name="email" class="form-control" value="<?php echo h($org['email'] ?? ''); ?>">
          </div>

          <div class="form-group">
            <label>Phone</label>
            <input type="tel" name="phone" class="form-control" value="<?php echo h($org['phone'] ?? ''); ?>">
          </div>

          <div class="form-group" style="grid-column:1/-1">
            <label>Address</label>
            <input type="text" name="address" class="form-control" value="<?php echo h($org['address'] ?? ''); ?>">
          </div>
        </div>

        <!-- Status change warning -->
        <?php if ($org['status'] === 'active'): ?>
        <div class="alert alert-warning" style="margin-bottom:18px">
          <svg viewBox="0 0 24 24" stroke-width="2"><path d="M10.29 3.86L1.82 18a2 2 0 001.71 3h16.94a2 2 0 001.71-3L13.71 3.86a2 2 0 00-3.42 0z"/><line x1="12" y1="9" x2="12" y2="13"/><line x1="12" y1="17" x2="12.01" y2="17"/></svg>
          Changing status to <strong>Suspended</strong> will immediately lock out all org admin accounts.
        </div>
        <?php endif; ?>

        <div style="display:flex;gap:10px">
          <a href="organization_view.php?id=<?php echo $org_id; ?>" class="btn btn-secondary btn-md">Cancel</a>
          <button type="submit" class="btn btn-primary btn-lg" style="flex:1">Save Changes</button>
        </div>
      </form>
    </div>
  </div>

  <!-- Danger zone -->
  <div class="card" style="margin-top:20px;border:1px solid var(--error-bg)">
    <div class="card-header" style="background:var(--error-bg)">
      <h3 style="color:var(--error)">Danger Zone</h3>
    </div>
    <div class="card-body">
      <div style="display:flex;align-items:center;justify-content:space-between;gap:16px;flex-wrap:wrap">
        <div>
          <p style="font-weight:700;font-size:.88rem">Suspend Organisation</p>
          <p style="font-size:.8rem;color:var(--text-muted)">Immediately locks out all administrators and prevents org portal access. Staff wallets and data are preserved.</p>
        </div>
        <?php if ($org['status'] === 'active'): ?>
        <form method="POST" onsubmit="return confirm('Suspend this organisation?')">
          <?php echo csrf_field(); ?>
          <input type="hidden" name="name"           value="<?php echo h($org['name']); ?>">
          <input type="hidden" name="type"           value="<?php echo h($org['type']); ?>">
          <input type="hidden" name="contact_person" value="<?php echo h($org['contact_person']??''); ?>">
          <input type="hidden" name="email"          value="<?php echo h($org['email']??''); ?>">
          <input type="hidden" name="phone"          value="<?php echo h($org['phone']??''); ?>">
          <input type="hidden" name="address"        value="<?php echo h($org['address']??''); ?>">
          <input type="hidden" name="status"         value="suspended">
          <button type="submit" class="btn btn-danger btn-md">Suspend Now</button>
        </form>
        <?php elseif ($org['status'] === 'suspended'): ?>
        <form method="POST">
          <?php echo csrf_field(); ?>
          <input type="hidden" name="name"           value="<?php echo h($org['name']); ?>">
          <input type="hidden" name="type"           value="<?php echo h($org['type']); ?>">
          <input type="hidden" name="contact_person" value="<?php echo h($org['contact_person']??''); ?>">
          <input type="hidden" name="email"          value="<?php echo h($org['email']??''); ?>">
          <input type="hidden" name="phone"          value="<?php echo h($org['phone']??''); ?>">
          <input type="hidden" name="address"        value="<?php echo h($org['address']??''); ?>">
          <input type="hidden" name="status"         value="active">
          <button type="submit" class="btn btn-success btn-md">Reactivate Organisation</button>
        </form>
        <?php endif; ?>
      </div>
    </div>
  </div>

</div>
</div>

<?php include_once("footer.php"); ?>
