<?php
declare(strict_types=1);

require_once dirname(__DIR__) . '/lib/tenant.php';
require_once dirname(__DIR__) . '/lib/client.php';
require_once dirname(__DIR__) . '/lib/admin_layout.php';

require_admin();
$tenantId = current_tenant_id();
$flash = '';
$policy = client_policy($tenantId);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    db()->prepare(
        'INSERT INTO client_policy (tenant_id, notice_hours, cancel_fee, allow_reschedule, allow_cancel, fee_note)
         VALUES (?,?,?,?,?,?)
         ON DUPLICATE KEY UPDATE
           notice_hours=VALUES(notice_hours), cancel_fee=VALUES(cancel_fee),
           allow_reschedule=VALUES(allow_reschedule), allow_cancel=VALUES(allow_cancel),
           fee_note=VALUES(fee_note)'
    )->execute([
        $tenantId,
        max(0, (int) ($_POST['notice_hours'] ?? 24)),
        max(0, (float) ($_POST['cancel_fee'] ?? 0)),
        isset($_POST['allow_reschedule']) ? 1 : 0,
        isset($_POST['allow_cancel']) ? 1 : 0,
        trim((string) ($_POST['fee_note'] ?? '')),
    ]);
    $flash = 'Client portal policy saved.';
    $policy = client_policy($tenantId);
}

admin_header('Client Portal Policy', 'policy');
if ($flash): ?><div class="flash"><?= htmlspecialchars($flash) ?></div><?php endif; ?>

<div class="panel">
  <h2>Cancel / reschedule rules</h2>
  <p class="muted">Clients manage appointments at <a href="<?= APP_BASE ?>/client/login.php<?= htmlspecialchars(tenant_qs()) ?>" target="_blank">/client/login.php</a>. Fees inside the notice window are noted on the booking until online payments are enabled.</p>
  <form method="post">
    <div class="grid-2">
      <div>
        <label>Notice window (hours)</label>
        <input type="number" name="notice_hours" min="0" max="168" value="<?= (int) $policy['notice_hours'] ?>">
        <label>Fee if inside window ($)</label>
        <input type="number" step="0.01" min="0" name="cancel_fee" value="<?= htmlspecialchars((string) $policy['cancel_fee']) ?>">
        <label style="display:flex;gap:.5rem;align-items:center;color:var(--text)">
          <input type="checkbox" name="allow_cancel" <?= !empty($policy['allow_cancel']) ? 'checked' : '' ?>>
          Allow online cancel
        </label>
        <label style="display:flex;gap:.5rem;align-items:center;color:var(--text);margin-top:.5rem">
          <input type="checkbox" name="allow_reschedule" <?= !empty($policy['allow_reschedule']) ? 'checked' : '' ?>>
          Allow online reschedule
        </label>
      </div>
      <div>
        <label>Policy note (shown to clients)</label>
        <textarea name="fee_note" rows="5"><?= htmlspecialchars((string) ($policy['fee_note'] ?? '')) ?></textarea>
      </div>
    </div>
    <button class="btn" type="submit">Save policy</button>
  </form>
</div>
<?php admin_footer(); ?>
