<?php
session_start();
include 'koneksi.php';

// 🔥 VALIDASI LOGIN
if(!isset($_SESSION['user'])){
    header("Location: index.php");
    exit;
}

// 🔥 VALIDASI HARUS DARI CHECKOUT
if(!isset($_SESSION['checkout_time'])){
    header("Location: keranjang.php");
    exit;
}

if(isset($_POST['upload'])){

    if($_FILES['bukti']['name'] == ''){
        echo "File belum dipilih!";
        exit;
    }

    $nama_file = time() . "_" . $_FILES['bukti']['name'];
    $tmp       = $_FILES['bukti']['tmp_name'];

    // 🔥 buat folder jika belum ada
    if(!is_dir("bukti")){
        mkdir("bukti", 0755, true);
    }

    move_uploaded_file($tmp, "bukti/" . $nama_file);

    $username = $_SESSION['user'];
    $tanggal  = $_SESSION['checkout_time'];

    // 🔥 UPDATE HANYA TRANSAKSI INI (AMAN)
    mysqli_query($conn, "
        UPDATE orders 
        SET bukti='$nama_file', status='Dibayar', alasan=NULL
        WHERE username='$username' 
        AND tanggal='$tanggal'
    ");

    // 🔥 HAPUS SESSION BIAR GAK NYANGKUT
    unset($_SESSION['checkout_time']);

    header("Location: orders.php");
    exit;
}
?>
<!DOCTYPE html>
<html lang="id">
<head>
<meta charset="UTF-8">
<title>Upload Bukti Pembayaran</title>

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.css">

<style>
body{
    font-family: Arial, sans-serif;
    background:#f4f6f9;
    margin:0;
}

.container{
    width:60%;
    margin:50px auto;
}

.box{
    background:white;
    padding:30px;
    border-radius:14px;
    box-shadow:0 4px 10px rgba(0,0,0,0.08);
    text-align:center;
}

.btn{
    margin-top:20px;
    padding:10px 18px;
    color:white;
    border:none;
    border-radius:8px;
    font-weight:bold;
    cursor:pointer;
    text-decoration:none;
    display:inline-block;
}

.upload{ background:#28a745; }
.back{ background:#007bff; margin-left:10px; }

/* 🔥 tambahan info */
.info{
    margin-top:10px;
    padding:10px;
    background:#fff3cd;
    border-radius:8px;
    color:#856404;
    font-size:14px;
}
</style>
</head>

<body>

<div class="container">
    <div class="box">

        <h2>📤 Upload Bukti Pembayaran</h2>

        <div class="info">
            ⚠️ Pastikan bukti transfer jelas agar mudah diverifikasi admin.
        </div>

        <form method="POST" enctype="multipart/form-data">
            <input type="file" name="bukti" required><br>

            <button type="submit" name="upload" class="btn upload">
                ✅ Upload Bukti
            </button>

            <a href="pembayaran.php" class="btn back">⬅️ Kembali</a>
        </form>

    </div>
</div>

</body>
</html>