<?php
// ============================================================
//  member/cancel-membership.php
// ============================================================
//
//  Two flows in one page:
//    1. Cancel  — POST without action: pauses PayFast subscription,
//                 sets cancel_effective_at, member keeps access
//                 until renewal date (grace period).
//    2. Reactivate — POST ?action=reactivate: unpauses PayFast,
//                    clears cancel_effective_at. No new charge —
//                    they keep the rest of their paid month/year.
//
//  Once grace period ends, cron/cancel-finalise.php actually
//  CANCELS the subscription at PayFast (irreversible). After
//  that, "reactivate" redirects to checkout for a fresh sub.
//
// ============================================================

$page_title = 'Cancel membership';
require __DIR__ . '/_guard.php';
require_once __DIR__ . '/../includes/payfast.php';
require_once __DIR__ . '/../includes/member_history.php';

$done       = false;       // cancellation just happened
$reactivated = false;      // reactivation just happened
$error      = '';
$grace_end  = $member['cancel_effective_at'] ?? null;
$is_pending_cancellation = !empty($member['cancel_effective_at']);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    csrf_verify();
    $action = $_POST['action'] ?? 'cancel';

    // ── Reactivate ──────────────────────────────────────────────
    if ($action === 'reactivate') {

        // Already-fully-cancelled member → must start a new subscription
        if ($member['status'] === 'cancelled' && !$is_pending_cancellation) {
            header('Location: checkout-membership.php?reactivate=1');
            exit;
        }

        // Find their token to unpause at PayFast
        $tokens = db_all(
            "SELECT id, token, status FROM payment_tokens
              WHERE member_id = :m AND token IS NOT NULL AND token != ''
              ORDER BY id DESC",
            ['m' => $member['id']]
        );

        $any_unpause_ok = false;
        $pf_messages = [];
        foreach ($tokens as $t) {
            // Skip tokens that are clearly dead
            if (in_array(strtolower($t['status'] ?? ''), ['failed'], true)) continue;

            $r = pf_unpause_subscription($t['token']);
            $pf_messages[] = $r['message'];
            app_log(sprintf(
                'Reactivate attempt for member %d token=%s ok=%s msg=%s',
                $member['id'], substr($t['token'], 0, 8) . '…',
                $r['ok'] ? 'yes' : 'no', $r['message']
            ));
            if ($r['ok']) {
                $any_unpause_ok = true;
                db_exec(
                    "UPDATE payment_tokens SET status='active', cancelled_at=NULL WHERE id=:id",
                    ['id' => $t['id']]
                );
            }
        }

        if ($any_unpause_ok) {
            // Clear the grace flag — back to normal active state
            db_exec(
                "UPDATE members SET cancel_effective_at=NULL WHERE id=:id",
                ['id' => $member['id']]
            );

            member_history_log(
                (int)$member['id'],
                'subscription_reactivated',
                'Subscription reactivated — billing resumes on next renewal date',
                ['action'=>'unpause', 'gateway'=>'payfast']
            );
            app_log("Reactivation: member {$member['id']} <{$member['email']}>");

            $member = db_row('SELECT * FROM members WHERE id=:id', ['id' => $member['id']]);
            $is_pending_cancellation = false;
            $grace_end = null;
            $reactivated = true;

        } else {
            // PayFast couldn't unpause — most likely subscription was already
            // cancelled at PayFast (e.g. cancellation happened under old logic
            // that hard-cancelled instead of pausing). Push the member to the
            // checkout page to re-subscribe from scratch.
            app_log(
                "Reactivate failed for member {$member['id']} — falling back to fresh checkout. " .
                "PayFast: " . implode('; ', $pf_messages)
            );
            header('Location: checkout-membership.php?reactivate=1');
            exit;
        }
    }

    // ── Cancel ──────────────────────────────────────────────────
    if ($action === 'cancel') {
        if (empty($_POST['confirm'])) {
            $error = 'Please tick the confirmation box to proceed.';
        } else {
            $tokens = db_all(
                "SELECT id, token, status, gateway FROM payment_tokens
                  WHERE member_id = :m AND token IS NOT NULL AND token != ''",
                ['m' => $member['id']]
            );

            app_log(sprintf(
                'Cancel initiated for member %d — found %d token(s)',
                $member['id'], count($tokens)
            ));

            $pf_failures = [];
            $pf_paused   = false;
            foreach ($tokens as $t) {
                if (in_array(strtolower($t['status'] ?? ''), ['cancelled', 'failed'], true)) {
                    continue;
                }
                $r = pf_pause_subscription($t['token']);
                app_log(sprintf(
                    'PayFast pause for member %d token=%s ok=%s msg=%s',
                    $member['id'], substr($t['token'], 0, 8) . '…',
                    $r['ok'] ? 'yes' : 'no', $r['message']
                ));
                if ($r['ok']) {
                    $pf_paused = true;
                } else {
                    $pf_failures[] = $r['message'];
                }
            }

            if (!empty($pf_failures) && !$pf_paused && !pf_is_sandbox()) {
                $error = 'We couldn\'t pause your subscription at the payment gateway: ' .
                         htmlspecialchars(implode('; ', $pf_failures)) .
                         '. Please contact us so we can sort this out.';
            } else {
                $effective_date = $member['renewal_date'] ?: date('Y-m-d');

                db_exec(
                    "UPDATE members SET cancel_effective_at=:d WHERE id=:id",
                    ['d' => $effective_date, 'id' => $member['id']]
                );
                // Note: payment_tokens.status stays 'active' — it's PAUSED at PayFast,
                // not cancelled. Cron actually cancels it on the effective date.

                member_history_log(
                    (int)$member['id'],
                    'cancellation_scheduled',
                    'Cancellation scheduled — access ends ' . date('j M Y', strtotime($effective_date)),
                    ['effective_date'=>$effective_date, 'action'=>'pause', 'gateway'=>'payfast']
                );

                $fresh = db_row('SELECT * FROM members WHERE id=:id', ['id' => $member['id']]);

                require_once __DIR__ . '/../includes/mailer.php';
                email_enqueue('cancellation_scheduled', $fresh['email'],
                    trim($fresh['first_name'] . ' ' . $fresh['last_name']),
                    [
                        'first_name'    => $fresh['first_name'],
                        'business_name' => $fresh['business_name'],
                        'end_date'      => date('j F Y', strtotime($effective_date)),
                    ]
                );

                app_log("Cancellation scheduled: member {$member['id']} <{$member['email']}> — access ends {$effective_date}");
                $member = $fresh;
                $is_pending_cancellation = true;
                $done   = true;
                $grace_end = $effective_date;
            }
        }
    }
}
?>
<style>
.m-page{padding:3rem 0;}
.cancel-wrap{max-width:600px;margin:0 auto;}
.impact-list{background:var(--surface-alt);border-radius:var(--radius);padding:1.25rem 1.25rem 1.25rem 2rem;margin:1rem 0;}
.impact-list li{padding:.3rem 0;font-size:.9rem;}
.danger-btn{background:#b91c1c;color:#fff;border:none;padding:.65rem 1.4rem;border-radius:var(--radius);font-weight:700;cursor:pointer;font-size:.95rem;}
.danger-btn:hover{background:#991b1b;}
.reactivate-btn{background:#059669;color:#fff;border:none;padding:.65rem 1.4rem;border-radius:var(--radius);font-weight:700;cursor:pointer;font-size:.95rem;text-decoration:none;display:inline-block;}
.reactivate-btn:hover{background:#047857;}
</style>

<div class="m-page">
<div class="container">
<div class="cancel-wrap">

<?php if ($reactivated): ?>
    <!-- Just reactivated ─────────────────────────────────────── -->
    <div style="text-align:center;padding:2rem 0;">
        <div style="font-size:3rem;margin-bottom:1rem;">🎉</div>
        <h1>Welcome back!</h1>
        <p class="muted" style="font-size:1.05rem;">
            Your membership is active again. <strong>You haven't been charged</strong> —
            your subscription simply resumed where it left off.
        </p>
        <?php if (!empty($member['renewal_date'])): ?>
        <p style="font-size:.95rem;color:var(--ink);margin-top:1rem;">
            Your next billing date is <strong><?= htmlspecialchars(date('j F Y', strtotime($member['renewal_date']))) ?></strong>.
        </p>
        <?php endif; ?>
        <div style="margin-top:1.75rem;">
            <a href="welcome.php" class="btn">Back to dashboard</a>
        </div>
    </div>

<?php elseif ($done): ?>
    <!-- Just cancelled ──────────────────────────────────────── -->
    <div style="text-align:center;padding:2rem 0;">
        <div style="font-size:3rem;margin-bottom:1rem;">👋</div>
        <h1>Cancellation scheduled</h1>
        <p class="muted">
            We're sorry to see you go. You <strong>won't be charged again</strong> — but you'll keep full
            access and your directory listing stays live until the end of your paid-up period.
        </p>
        <div style="background:#fff;border:1px solid var(--line);border-radius:var(--radius);padding:1.25rem;margin:1.5rem auto;max-width:440px;">
            <p style="margin:0;font-size:.85rem;text-transform:uppercase;letter-spacing:.08em;color:var(--ink-muted);">Access ends</p>
            <p style="margin:.3rem 0 0;font-size:1.5rem;font-weight:700;color:var(--ink);">
                <?= htmlspecialchars(date('j F Y', strtotime($grace_end))) ?>
            </p>
        </div>
        <p style="font-size:.92rem;color:var(--ink);background:#ecfdf5;border:1px solid #6ee7b7;border-radius:var(--radius);padding:.85rem 1rem;display:inline-block;">
            <strong>Changed your mind?</strong> You can reactivate any time before the end date —
            no new charge, your subscription just picks up where it left off.
        </p>
        <div style="display:flex;gap:.75rem;justify-content:center;margin-top:1.5rem;flex-wrap:wrap;">
            <form method="post" action="cancel-membership.php" style="display:inline;">
                <?= csrf_field() ?>
                <input type="hidden" name="action" value="reactivate">
                <button type="submit" class="reactivate-btn">↻ Reactivate now</button>
            </form>
            <a href="welcome.php" class="btn btn-outline">Back to dashboard</a>
        </div>
    </div>

<?php elseif ($is_pending_cancellation): ?>
    <!-- Already cancelled, viewing this page again — show reactivate ─ -->
    <a href="welcome.php" style="font-size:.88rem;color:var(--ink-muted);">← Back to dashboard</a>
    <h1 style="margin:.75rem 0 .25rem;">Cancellation scheduled</h1>
    <p class="muted" style="margin:0 0 1.5rem;">
        Your membership is set to end on
        <strong><?= htmlspecialchars(date('j F Y', strtotime($grace_end))) ?></strong>.
    </p>

    <?php if ($error): ?>
        <div class="alert alert-error" style="margin-bottom:1rem;"><?= htmlspecialchars($error) ?></div>
    <?php endif; ?>

    <div style="background:#fff;border:1px solid var(--line);border-radius:var(--radius);padding:1.5rem;">
        <h2 style="margin-top:0;font-size:1rem;">Changed your mind?</h2>
        <p style="font-size:.9rem;margin-bottom:1rem;">
            Reactivate now and your subscription resumes — <strong>no new charge</strong>, your
            paid-up period continues, and PayFast will bill you again on the natural renewal date
            <?php if (!empty($member['renewal_date'])): ?>
                (<?= htmlspecialchars(date('j F Y', strtotime($member['renewal_date']))) ?>)
            <?php endif; ?>.
        </p>
        <form method="post" action="cancel-membership.php">
            <?= csrf_field() ?>
            <input type="hidden" name="action" value="reactivate">
            <button type="submit" class="reactivate-btn">↻ Reactivate my membership</button>
        </form>
    </div>

<?php elseif ($member['status'] === 'cancelled'): ?>
    <!-- Fully cancelled (post-grace) ────────────────────────── -->
    <a href="welcome.php" style="font-size:.88rem;color:var(--ink-muted);">← Back to dashboard</a>
    <h1 style="margin:.75rem 0 .25rem;">Your membership has ended</h1>
    <p class="muted" style="margin:0 0 1.5rem;">
        Your previous subscription has fully closed. To come back, you'll need to set up a fresh subscription.
    </p>

    <div style="background:#fff;border:1px solid var(--line);border-radius:var(--radius);padding:1.5rem;text-align:center;">
        <p style="margin:0 0 1rem;">Welcome back any time.</p>
        <a href="checkout-membership.php?reactivate=1" class="btn">Re-subscribe</a>
    </div>

<?php else: ?>
    <!-- Active member — cancellation form ───────────────────── -->
    <a href="welcome.php" style="font-size:.88rem;color:var(--ink-muted);">← Back to dashboard</a>
    <h1 style="margin:.75rem 0 .25rem;">Cancel your membership</h1>
    <p class="muted" style="margin:0 0 1.5rem;">We'd hate to lose you. Please read what happens before confirming.</p>

    <?php if ($error): ?>
        <div class="alert alert-error" style="margin-bottom:1rem;"><?= htmlspecialchars($error) ?></div>
    <?php endif; ?>

    <div style="background:#fff;border:1px solid var(--line);border-radius:var(--radius);padding:1.5rem;margin-bottom:1.25rem;">
        <h2 style="margin-top:0;font-size:1rem;">What cancelling means</h2>
        <ul class="impact-list">
            <li>Your subscription is <strong>paused at PayFast</strong> — no further charges will be made.</li>
            <li>You keep full access and your directory listing stays live until
                <?php if (!empty($member['renewal_date'])): ?>
                    <strong><?= htmlspecialchars(date('j F Y', strtotime($member['renewal_date']))) ?></strong>
                    (the end of your current paid-up period).
                <?php else: ?>
                    the end of your current paid-up period.
                <?php endif; ?>
            </li>
            <li><strong>You can reactivate any time before then</strong> with no new charge — your
                paid period just continues.</li>
            <li>After that date your account is closed and listing hidden. To come back, you'd
                need a fresh subscription.</li>
        </ul>
    </div>

    <div style="background:#fff;border:1px solid var(--line);border-radius:var(--radius);padding:1.5rem;">
        <form method="post" action="cancel-membership.php">
            <?= csrf_field() ?>
            <input type="hidden" name="action" value="cancel">
            <label style="display:flex;align-items:flex-start;gap:.75rem;cursor:pointer;font-size:.9rem;margin-bottom:1.25rem;">
                <input type="checkbox" name="confirm" style="margin-top:.2rem;flex-shrink:0;">
                <span>I understand — please cancel my Buy Local Lowveld membership.</span>
            </label>
            <div style="display:flex;gap:.75rem;align-items:center;">
                <button type="submit" class="danger-btn">Cancel my membership</button>
                <a href="welcome.php" class="btn btn-outline">Keep my membership</a>
            </div>
        </form>
    </div>

<?php endif; ?>
</div>
</div>
</div>
<?php require __DIR__ . '/_footer.php'; ?>