<?php
// ============================================================
//  member/request-cancel.php  — AJAX endpoint
//
//  Accepts POST with { reason: "..." } from the cancel-request
//  modal on the member dashboard.
//
//  Records the request on the member row, sends:
//    1. Confirmation email to the member
//    2. Alert email to the admin
//
//  Does NOT touch PayFast or cancel_effective_at — the actual
//  cancellation is performed by an admin via the admin panel.
// ============================================================

require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/csrf.php';
require_once __DIR__ . '/../includes/mailer.php';

header('Content-Type: application/json');

// ── Auth ──────────────────────────────────────────────────────────────────────
if (!auth_check()) {
    http_response_code(401);
    echo json_encode(['ok' => false, 'error' => 'Not logged in.']);
    exit;
}

// ── Method ────────────────────────────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['ok' => false, 'error' => 'Method not allowed.']);
    exit;
}

// ── CSRF ──────────────────────────────────────────────────────────────────────
$sent = $_POST['_csrf'] ?? '';
if (!hash_equals(csrf_token(), (string)$sent)) {
    http_response_code(403);
    echo json_encode(['ok' => false, 'error' => 'Security token mismatch. Refresh and try again.']);
    exit;
}

// ── Load member ───────────────────────────────────────────────────────────────
$member = auth_user();

// Already has a pending request?
if (!empty($member['cancel_request_at']) && empty($member['cancel_effective_at'])) {
    echo json_encode(['ok' => true, 'already' => true,
        'message' => 'Your cancellation request is already with the team.']);
    exit;
}

// Already fully cancelled?
if ($member['status'] === 'cancelled') {
    echo json_encode(['ok' => false, 'error' => 'Your membership is already cancelled.']);
    exit;
}

// ── Input ─────────────────────────────────────────────────────────────────────
$reason = trim($_POST['reason'] ?? '');
if ($reason === '') {
    echo json_encode(['ok' => false, 'error' => 'Please tell us why you want to cancel.']);
    exit;
}
if (mb_strlen($reason) > 2000) {
    $reason = mb_substr($reason, 0, 2000);
}

// ── Save to DB ────────────────────────────────────────────────────────────────
$now = date('Y-m-d H:i:s');
db_exec(
    'UPDATE members SET cancel_request_at = :at, cancel_request_reason = :r WHERE id = :id',
    ['at' => $now, 'r' => $reason, 'id' => $member['id']]
);

app_log("Cancel request: member {$member['id']} <{$member['email']}> — reason: " . substr($reason, 0, 120));

// ── Email 1: confirmation to member ──────────────────────────────────────────
$member_name = trim($member['first_name'] . ' ' . $member['last_name']);

email_send_now(
    $member['email'],
    $member_name,
    'Cancellation Request Received — Buy Local Lowveld',
    nl2br("Hi {$member['first_name']},\n\nThank you for reaching out. We have received your cancellation request and our team will be in contact with you shortly to assist.\n\nYour membership remains fully active in the meantime.\n\nKind regards,\nThe Buy Local Lowveld Team"),
    "Hi {$member['first_name']},\n\nThank you for reaching out. We have received your cancellation request and our team will be in contact with you shortly to assist.\n\nYour membership remains fully active in the meantime.\n\nKind regards,\nThe Buy Local Lowveld Team"
);

// ── Email 2: alert to admin ───────────────────────────────────────────────────
$admin_email = setting_get('email.admin_notify', setting_get('email.reply_to', setting_get('email.from_email', '')));

if ($admin_email) {
    $body_html = '<p><strong>A member has requested cancellation of their membership.</strong></p>'
        . '<table style="border-collapse:collapse;font-size:.9rem;" cellpadding="6">'
        . '<tr><td style="color:#666;">Name</td><td><strong>' . htmlspecialchars($member_name) . '</strong></td></tr>'
        . '<tr><td style="color:#666;">Business</td><td>' . htmlspecialchars($member['business_name'] ?? '—') . '</td></tr>'
        . '<tr><td style="color:#666;">Email</td><td>' . htmlspecialchars($member['email']) . '</td></tr>'
        . '<tr><td style="color:#666;">Tier</td><td>' . htmlspecialchars($member['tier'] ?? '—') . '</td></tr>'
        . '<tr><td style="color:#666;">Requested at</td><td>' . htmlspecialchars($now) . '</td></tr>'
        . '<tr><td style="color:#666;vertical-align:top;">Reason</td><td>' . nl2br(htmlspecialchars($reason)) . '</td></tr>'
        . '</table>'
        . '<p style="margin-top:1.5rem;"><a href="' . rtrim(setting_get('app.url', ''), '/') . '/admin/cancel-requests.php" '
        . 'style="background:#b91c1c;color:#fff;padding:.5rem 1rem;border-radius:4px;text-decoration:none;font-weight:bold;">'
        . 'View in Admin Panel →</a></p>';

    $body_text = "A member has requested cancellation.\n\n"
        . "Name: {$member_name}\n"
        . "Business: " . ($member['business_name'] ?? '—') . "\n"
        . "Email: {$member['email']}\n"
        . "Tier: " . ($member['tier'] ?? '—') . "\n"
        . "Requested at: {$now}\n"
        . "Reason:\n{$reason}\n\n"
        . "Action in admin panel: " . rtrim(setting_get('app.url', ''), '/') . "/admin/cancel-requests.php";

    email_send_now(
        $admin_email,
        'Buy Local Admin',
        '⚠️ Cancellation Request — ' . ($member['business_name'] ?: $member_name),
        $body_html,
        $body_text
    );
}

// ── Log member history ────────────────────────────────────────────────────────
require_once __DIR__ . '/../includes/member_history.php';
member_history_log(
    (int)$member['id'],
    'cancellation_requested',
    'Member submitted a cancellation request',
    ['reason' => substr($reason, 0, 500)]
);

echo json_encode(['ok' => true, 'message' => 'Your request has been submitted. Our team will be in touch with you shortly.']);