<?php
// process_product_purchase.php — AJAX endpoint for product STK push
// Mirrors the exact bootstrap order of activate.php

ob_start(); // Buffer ALL output — catches any whitespace/warnings from includes

require_once '../config/database.php';    // may call session_start() internally
require_once '../includes/functions.php'; // same pattern as activate.php

// Session start AFTER includes (matches activate.php order)
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

require_once '../mpesa/stk_push.php';

// Now safe to set header — ob_start() means nothing was sent yet
header('Content-Type: application/json');

// Helper: wipe any stray output and return clean JSON
function jsonOut($data) {
    ob_end_clean(); // discard any warnings/whitespace buffered above
    echo json_encode($data);
    exit;
}

// Log errors to file instead of outputting them (breaks JSON)
set_error_handler(function($errno, $errstr, $errfile, $errline) {
    $log = __DIR__ . '/../mpesa/purchase_error.log';
    file_put_contents($log, date('Y-m-d H:i:s') . " [$errno] $errstr in $errfile:$errline\n", FILE_APPEND);
    // Don't output — just log
    return true;
});

// Auth check — mirrors activate.php: uses $_SESSION['user_id']
if (!isset($_SESSION['user_id'])) {
    jsonOut(['success' => false, 'message' => 'Session expired. Please refresh the page and try again.']);
}

$userId    = intval($_SESSION['user_id']);
$productId = intval($_POST['product_id'] ?? 0);

if ($productId < 1) {
    jsonOut(['success' => false, 'message' => 'Invalid product ID.']);
}

// Phone from modal — empty = stk_push.php falls back to account phone
$phone = trim($_POST['phone'] ?? '');

try {
    $result = processProductPayment($userId, $phone, $productId);
    jsonOut($result);
} catch (Throwable $e) {
    // Log the full error
    $log = __DIR__ . '/../mpesa/purchase_error.log';
    file_put_contents($log, date('Y-m-d H:i:s') . ' EXCEPTION: ' . $e->getMessage() . "\n" . $e->getTraceAsString() . "\n\n", FILE_APPEND);
    jsonOut(['success' => false, 'message' => 'Server error: ' . $e->getMessage()]);
}