<?php
/*
 * ============================================================
 * TryTrack — PayFast Checkout Creator
 * ============================================================
 *
 * SETUP INSTRUCTIONS (before going live):
 *
 * 1. Rename this section and set your real credentials:
 *    - PAYFAST_MERCHANT_ID   : your live merchant ID from PayFast
 *    - PAYFAST_MERCHANT_KEY  : your live merchant key
 *    - PAYFAST_PASSPHRASE    : your live passphrase (if set in PayFast)
 *
 * 2. Set PAYFAST_SANDBOX = false once ready for production.
 *
 * 3. Store credentials in environment variables, not hardcoded here.
 *    Use: $creds = require __DIR__ . '/../config/payfast.php';
 *
 * ============================================================
 */

header("Content-Type: application/json");

// ── Credentials — load from environment or config file ─────
// NEVER commit real credentials to source control.
// Use environment variables on your server:
//   export PAYFAST_MERCHANT_ID="your_id"
//   export PAYFAST_MERCHANT_KEY="your_key"
//   export PAYFAST_PASSPHRASE="your_passphrase"

$PAYFAST_SANDBOX       = true;  // ← Set to false for LIVE payments
$PAYFAST_MERCHANT_ID   = getenv("PAYFAST_MERCHANT_ID")   ?: "10000100";   // Sandbox default
$PAYFAST_MERCHANT_KEY  = getenv("PAYFAST_MERCHANT_KEY")  ?: "46f0cd694581a"; // Sandbox default
$PAYFAST_PASSPHRASE    = getenv("PAYFAST_PASSPHRASE")    ?: "";

$PAYFAST_URL = $PAYFAST_SANDBOX
  ? "https://sandbox.payfast.co.za/eng/process"
  : "https://www.payfast.co.za/eng/process";

// ── Parse request ────────────────────────────────────────────
$input = json_decode(file_get_contents("php://input"), true);

if (!is_array($input)) {
    http_response_code(400);
    echo json_encode(["error" => "Invalid JSON body"]);
    exit;
}

$plan           = $input["plan"]           ?? "";
$cycle          = $input["cycle"]          ?? "monthly";
$organisationId = $input["organisationId"] ?? "";

if (!$organisationId) {
    http_response_code(400);
    echo json_encode(["error" => "Missing organisationId"]);
    exit;
}

// ── Plan definitions ─────────────────────────────────────────
$plans = [
    "team" => [
        "name"    => "Team Performance",
        "monthly" => 1999,
        "yearly"  => 19990,
    ],
    "club" => [
        "name"    => "Club Performance",
        "monthly" => 5999,
        "yearly"  => 59990,
    ],
];

if (!isset($plans[$plan]) || !isset($plans[$plan][$cycle])) {
    http_response_code(400);
    echo json_encode(["error" => "Invalid plan or billing cycle"]);
    exit;
}

// ── Build payment data ───────────────────────────────────────
$amount    = number_format($plans[$plan][$cycle], 2, ".", "");
$itemName  = "TryTrack " . $plans[$plan]["name"] . " — " . ucfirst($cycle);
$paymentId = $organisationId . "_" . $plan . "_" . $cycle . "_" . time();

$baseUrl = "https://www.trytrack.co.za";

$data = [
    "merchant_id"  => $PAYFAST_MERCHANT_ID,
    "merchant_key" => $PAYFAST_MERCHANT_KEY,

    "return_url" => $baseUrl . "/payment-success.html",
    "cancel_url" => $baseUrl . "/payment-cancelled.html",
    "notify_url" => $baseUrl . "/api/payfast-itn.php",

    "m_payment_id" => $paymentId,
    "amount"       => $amount,
    "item_name"    => $itemName,

    "custom_str1"  => $organisationId,
    "custom_str2"  => $plan,
    "custom_str3"  => $cycle,
];

// Monthly = recurring subscription
if ($cycle === "monthly") {
    $data["subscription_type"]  = "1";
    $data["billing_date"]       = date("Y-m-d");
    $data["recurring_amount"]   = $amount;
    $data["frequency"]          = "3"; // Monthly
    $data["cycles"]             = "0"; // Ongoing
}

// ── Generate signature ───────────────────────────────────────
$sigParts = [];
foreach ($data as $key => $value) {
    if ($value !== "") {
        $sigParts[] = $key . "=" . urlencode(trim((string) $value));
    }
}

$sigString = implode("&", $sigParts);

if ($PAYFAST_PASSPHRASE !== "") {
    $sigString .= "&passphrase=" . urlencode(trim($PAYFAST_PASSPHRASE));
}

$data["signature"] = md5($sigString);

// ── Build redirect URL ───────────────────────────────────────
$queryParts = [];
foreach ($data as $key => $value) {
    if ($value !== "") {
        $queryParts[] = $key . "=" . urlencode(trim((string) $value));
    }
}

echo json_encode([
    "paymentUrl" => $PAYFAST_URL . "?" . implode("&", $queryParts),
    "paymentId"  => $paymentId,
    "amount"     => $amount,
    "sandbox"    => $PAYFAST_SANDBOX,
]);
