<?php
session_start();
// Prevent any direct HTML output
ob_start();

// Tidak perlu header JSON lagi
// Hapus fungsi outputErrorJson dan semua Midtrans

try {
    require_once(__DIR__ . '/../config/db_config.php');
    require_once __DIR__ . '/../models/Order.php';

    ini_set('display_errors', 0);
    ini_set('log_errors', 1);
    error_reporting(E_ALL);
    date_default_timezone_set('Asia/Jakarta');

    function logPaymentProcess($message, $data = []) {
        $log = date('Y-m-d H:i:s') . ' - ' . $message;
        if (!empty($data)) {
            $log .= ' - ' . json_encode($data);
        }
        $log .= "\n";
        file_put_contents(__DIR__ . '/payment_process.log', $log, FILE_APPEND);
    }

    logPaymentProcess('Payment process started');

    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        logPaymentProcess('Method not allowed', $_SERVER);
        header('Location: checkout.php?error=method');
        exit;
    }

    // Validasi order data dari $_POST
    if (!isset($_POST['customer_name']) || !isset($_POST['customer_phone']) || !isset($_POST['customer_address']) || !isset($_POST['payment_method'])) {
        logPaymentProcess('Invalid order data (POST)', $_POST);
        header('Location: checkout.php?error=invalid');
        exit;
    }
    
    // Format items array untuk database
    $db_items = [];
    $items = [];
    if (isset($_POST['items'])) {
        $items = json_decode($_POST['items'], true);
        if (is_array($items)) {
            foreach ($items as $item) {
            $db_items[] = [
                    'product_id' => null, // Tidak ada product_id dari frontend
                    'product_name' => isset($item['product']) ? $item['product'] : (isset($item['name']) ? $item['name'] : ''),
                    'product_price' => (int)($item['price'] ?? 0),
                'quantity' => (int)($item['quantity'] ?? 1),
                    'subtotal' => (int)($item['price'] ?? 0) * (int)($item['quantity'] ?? 1),
                    'kode_pesanan' => isset($_POST['order_id']) ? $_POST['order_id'] : ''
                ];
            }
        }
    }
    
    // Simpan order ke database
    $order = new Order();
    $order->order_code = $_POST['order_id'] ?? ('ORDER-' . time() . '-' . rand(1000,9999));
    $order->user_id = isset($_SESSION['user_id']) ? (int)$_SESSION['user_id'] : null;
    $order->name = $_POST['customer_name'] ?? '';
    $order->email = $_POST['customer_email'] ?? '';
    $order->phone = $_POST['customer_phone'] ?? '';
    $order->address = $_POST['customer_address'] ?? '';
    $order->total_amount = isset($_POST['gross_amount']) ? (int)$_POST['gross_amount'] : 0;
    $order->status = 'pending';
    $order->payment_method = $_POST['payment_method'] ?? 'manual';
    $order->shipping_label = $_POST['shipping_label'] ?? null;
    $order->resi = null; // default null, nanti diisi admin jika JNE
    $order->items = $db_items;
    $order_saved = $order->create();
    logPaymentProcess('Order saved to database', ['success' => $order_saved, 'order_id' => $order->order_code]);
    if ($order_saved) {
        // Redirect ke halaman instruksi transfer/upload bukti pembayaran
        $method = urlencode($order->payment_method);
        $oid = urlencode($order->order_code);
        header("Location: payment_instruction.php?order_id=$oid&method=$method");
        exit;
    } else {
        logPaymentProcess('Failed to save order');
        header('Location: checkout.php?error=save');
        exit;
    }
} catch (Exception $e) {
    logPaymentProcess('Exception: ' . $e->getMessage());
    header('Location: checkout.php?error=server');
    exit;
} 