<?php
require_once __DIR__.'/inc/config.php';
require_once __DIR__.'/inc/db.php';
require_once __DIR__.'/inc/helpers.php';
require_once __DIR__.'/inc/csrf.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST' || !csrf_verify()) {
    exit('Permintaan tidak sah.');
}
$order_id = (int)($_POST['order_id'] ?? 0);
if ($order_id === 0) { exit('ID Pesanan tidak sah.'); }

if (isset($_FILES['proof_file']) && $_FILES['proof_file']['error'] === UPLOAD_ERR_OK) {
    $file = $_FILES['proof_file'];
    $upload_dir = __DIR__ . '/public/uploads/proofs/';
    if (!is_dir($upload_dir)) { mkdir($upload_dir, 0755, true); }

    $max_size = 5 * 1024 * 1024;
    $allowed_types = ['image/jpeg', 'image/png', 'image/gif', 'application/pdf'];
    if ($file['size'] > $max_size || !in_array(mime_content_type($file['tmp_name']), $allowed_types)) {
        header('Location: thank_you.php?order='.$order_id.'&upload_error=Fail tidak sah.'); exit;
    }

    $extension = pathinfo($file['name'], PATHINFO_EXTENSION);
    $unique_filename = 'proof_' . $order_id . '_' . uniqid() . '.' . $extension;
    $destination = $upload_dir . $unique_filename;

    if (move_uploaded_file($file['tmp_name'], $destination)) {
        $file_path_to_save = 'public/uploads/proofs/' . $unique_filename;
        $st = db()->prepare("INSERT INTO payment_proofs (order_id, file_path) VALUES (?, ?)");
        $st->execute([$order_id, $file_path_to_save]);
        
        $update_st = db()->prepare("UPDATE orders SET status = 'Payment Review' WHERE id = ? AND status = 'Pending'");
        $update_st->execute([$order_id]);
        
        $id = $order_id;
        include __DIR__.'/send_notification.php';
        
        header('Location: thank_you.php?order='.$order_id.'&upload_success=1');
        exit;
    }
}
header('Location: thank_you.php?order='.$order_id.'&upload_error=Gagal memuat naik fail.');
exit;