<?php
require_once __DIR__ . '/../system/guard.php';
require_once __DIR__ . '/../system/permissions.php';
require_once __DIR__ . '/../system/db.php';

requireAuth();
requirePermission('billing.manage');

$companyId  = (int)$_POST['company_id'];
$moduleKey  = $_POST['module_key'];
$cycle      = $_POST['billing_cycle']; // monthly | annual

$db = db();

/* Get module + pricing */
$stmt = $db->prepare("
  SELECT m.id, m.name, mp.monthly_price, mp.annual_price
  FROM modules m
  JOIN module_pricing mp ON mp.module_id = m.id
  WHERE m.module_key = :key
");
$stmt->execute(['key' => $moduleKey]);
$module = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$module) {
  jsonResponse(['error' => 'Module not found'], 404);
}

$amount = $cycle === 'annual'
  ? $module['annual_price']
  : $module['monthly_price'];

/* Create pending payment */
$stmt = $db->prepare("
  INSERT INTO payments (company_id, module_id, amount, billing_cycle)
  VALUES (:company, :module, :amount, :cycle)
");
$stmt->execute([
  'company' => $companyId,
  'module'  => $module['id'],
  'amount'  => $amount,
  'cycle'   => $cycle
]);

$paymentId = $db->lastInsertId();

/* PayFast payload */
$config = require __DIR__ . '/../system/payfast.php';

$data = [
  'merchant_id' => $config['merchant_id'],
  'merchant_key'=> $config['merchant_key'],
  'return_url'  => $config['return_url'],
  'cancel_url'  => $config['cancel_url'],
  'notify_url'  => $config['notify_url'],
  'amount'      => number_format($amount, 2, '.', ''),
  'item_name'   => $module['name'] . ' Module',
  'custom_str1' => $paymentId
];

jsonResponse([
  'payfast_url' => $config['sandbox']
    ? 'https://sandbox.payfast.co.za/eng/process'
    : 'https://www.payfast.co.za/eng/process',
  'payload' => $data
]);
