<?php
require_once __DIR__ . '/../includes/auth.php';
require_customer();
require_once __DIR__ . '/../includes/header_customer.php';
require_once __DIR__ . '/../includes/upload.php';
$pdo = require __DIR__ . '/../config/pdo.php';

$orderId = isset($_GET['order_id']) ? (int) $_GET['order_id'] : 0;
$stmt = $pdo->prepare('SELECT id, code, total FROM orders WHERE id = ? AND user_id = ? LIMIT 1');
$stmt->execute([$orderId, current_user()['id']]);
$order = $stmt->fetch();

if (!$order) {
    echo '<div class="alert error">Order tidak ditemukan.</div>';
    require_once __DIR__ . '/../includes/footer_customer.php';
    exit;
}

$errors = [];
$amount = trim($_POST['amount'] ?? $order['total']);
$paidAt = trim($_POST['paid_at'] ?? date('Y-m-d'));
$note = trim($_POST['note'] ?? '');

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if ($amount === '' || !is_numeric($amount) || (float) $amount <= 0) {
        $errors['amount'] = 'Jumlah bayar tidak valid.';
    }

    if ($paidAt === '' || !strtotime($paidAt)) {
        $errors['paid_at'] = 'Tanggal bayar tidak valid.';
    }

    if (!isset($_FILES['proof']) || $_FILES['proof']['error'] === UPLOAD_ERR_NO_FILE) {
        $errors['proof'] = 'Bukti transfer wajib diupload.';
    }

    if (!$errors) {
        $upload = handle_upload($_FILES['proof'], ['image/jpeg', 'image/png', 'image/webp'], 2 * 1024 * 1024, __DIR__ . '/../uploads');
        if (!$upload['ok']) {
            $errors['proof'] = $upload['error'];
        }
    }

    if (!$errors) {
        $stmt = $pdo->prepare('INSERT INTO payment_confirmations (order_id, paid_at, amount, proof_file, note, status) VALUES (?, ?, ?, ?, ?, "pending")');
        $stmt->execute([
            $order['id'],
            date('Y-m-d H:i:s', strtotime($paidAt)),
            $amount,
            $upload['filename'],
            $note,
        ]);

        $pdo->prepare('UPDATE orders SET status = "menunggu_verifikasi" WHERE id = ?')->execute([$order['id']]);

        flash_message('success', 'Konfirmasi pembayaran berhasil dikirim.');
        redirect(base_url('public/index.php?page=orders'));
    }
}
?>

<h2 class="fw-bold mb-3">Konfirmasi Pembayaran</h2>

<div class="card shadow-sm">
    <div class="card-body">
        <p>Kode Order: <strong><?= sanitize($order['code']); ?></strong></p>
        <form method="post" enctype="multipart/form-data">
            <label>Jumlah Bayar</label>
            <input class="form-control" type="number" name="amount" value="<?= sanitize($amount); ?>" min="1" step="1000" required>
            <?php if (!empty($errors['amount'])): ?><small class="error"><?= sanitize($errors['amount']); ?></small><?php endif; ?>

            <label>Tanggal Bayar</label>
            <input class="form-control" type="date" name="paid_at" value="<?= sanitize($paidAt); ?>" required>
            <?php if (!empty($errors['paid_at'])): ?><small class="error"><?= sanitize($errors['paid_at']); ?></small><?php endif; ?>

            <label>Upload Bukti Transfer</label>
            <input class="form-control" type="file" name="proof" accept="image/*" required>
            <?php if (!empty($errors['proof'])): ?><small class="error"><?= sanitize($errors['proof']); ?></small><?php endif; ?>

            <label>Catatan (opsional)</label>
            <textarea class="form-control" name="note" rows="3"><?= sanitize($note); ?></textarea>

            <button class="btn mt-3" type="submit">Kirim Konfirmasi</button>
        </form>
    </div>
</div>

<?php require_once __DIR__ . '/../includes/footer_customer.php'; ?>
