<?php
session_start();
include('includes/config.php');

if(!isset($_SESSION['user_id'])){
    header("Location: login.php");
    exit();
}

$user_id = $_SESSION['user_id'];
$checkout_cart = [];


if(isset($_GET['buy'])){
    $id = intval($_GET['buy']);
    $size = isset($_GET['size']) ? intval($_GET['size']) : 0;
    if($size == 0) { echo "<script>alert('Ukuran tidak valid!'); window.history.back();</script>"; exit; }
    
    $key = $id . "-" . $size;
    $checkout_cart[$key] = [
        'id_produk' => $id,
        'ukuran' => $size,
        'qty' => 1
    ];
} 
elseif(isset($_SESSION['cart']) && count($_SESSION['cart']) > 0){
    $checkout_cart = $_SESSION['cart'];
}

if(count($checkout_cart) == 0){
    echo "<p style='text-align:center; margin-top:50px;'>Tidak ada produk untuk checkout. <a href='product.php'>Kembali Belanja</a></p>";
    exit();
}

$error = "";


if(isset($_POST['checkout'])){
    $nama_penerima = mysqli_real_escape_string($conn, $_POST['nama_penerima']);
    $no_hp = mysqli_real_escape_string($conn, $_POST['no_hp']);
    $alamat_lengkap = mysqli_real_escape_string($conn, $_POST['alamat_lengkap']);
    $provinsi = mysqli_real_escape_string($conn, $_POST['provinsi']);
    $kota = mysqli_real_escape_string($conn, $_POST['kota']);
    $kode_pos = mysqli_real_escape_string($conn, $_POST['kode_pos'] ?? ''); // Mencegah Undefined
    $ekspedisi = mysqli_real_escape_string($conn, $_POST['ekspedisi']);
    $metode_pembayaran = mysqli_real_escape_string($conn, $_POST['metode_pembayaran']);
    $tanggal = date("Y-m-d H:i:s");

    
    $total = 0;
    foreach($checkout_cart as $item){
        $id_p = $item['id_produk'];
        $qty = $item['qty'];
        $res = mysqli_query($conn,"SELECT harga FROM produk WHERE id='$id_p'");
        $p = mysqli_fetch_assoc($res);
        $total += ($p['harga'] * $qty);
    }
    $ongkir = 10000;
    $totalAll = $total + $ongkir;

    
    $no_pesanan = "ALF-" . date("Ymd") . "-" . strtoupper(substr(uniqid(), -4));

    
    $bukti_pembayaran = null;
    if($metode_pembayaran == 'Transfer Bank'){
        if(isset($_FILES['bukti_pembayaran']) && $_FILES['bukti_pembayaran']['error'] === 0){
            $upload_dir = 'uploads/bukti_pembayaran/';
            if(!is_dir($upload_dir)) mkdir($upload_dir, 0777, true);
            $file_name = time() . '_' . $_FILES['bukti_pembayaran']['name'];
            move_uploaded_file($_FILES['bukti_pembayaran']['tmp_name'], $upload_dir . $file_name);
            $bukti_pembayaran = $upload_dir . $file_name;
        } else {
            $error = "Bukti pembayaran wajib diunggah untuk metode Transfer!";
        }
    }

    if(empty($error)){
        
        $query_order = "INSERT INTO pesanan (no_pesanan, id_user, nama_penerima, no_hp, alamat_lengkap, provinsi, kota, kode_pos, ekspedisi, metode_pembayaran, total, status, tanggal)
                        VALUES ('$no_pesanan','$user_id','$nama_penerima','$no_hp','$alamat_lengkap','$provinsi','$kota','$kode_pos','$ekspedisi','$metode_pembayaran','$totalAll','Menunggu Verifikasi','$tanggal')";
        
        if(mysqli_query($conn, $query_order)){
            $id_pesanan = mysqli_insert_id($conn);

            foreach($checkout_cart as $item){
                $id_p = $item['id_produk'];
                $uk = $item['ukuran'];
                $qty = $item['qty'];

                $resP = mysqli_query($conn,"SELECT harga FROM produk WHERE id='$id_p'");
                $pData = mysqli_fetch_assoc($resP);
                $harga_beli = $pData['harga'];

                
                mysqli_query($conn,"INSERT INTO detail_pesanan (id_pesanan, id_produk, ukuran, qty, harga)
                                    VALUES ('$id_pesanan','$id_p','$uk','$qty','$harga_beli')");

                
                mysqli_query($conn, "UPDATE produk_detail SET stok = stok - $qty WHERE id_produk = '$id_p' AND ukuran = '$uk'");
            }

            
            $status_pemb = ($metode_pembayaran == 'COD') ? 'Belum Dibayar' : 'Menunggu Verifikasi';
            mysqli_query($conn, "INSERT INTO pembayaran (id_pesanan, metode_pembayaran, jumlah, tanggal_pembayaran, bukti_pembayaran, status)
                                 VALUES ('$id_pesanan','$metode_pembayaran','$totalAll','$tanggal','$bukti_pembayaran','$status_pemb')");

            if(!isset($_GET['buy'])) unset($_SESSION['cart']);
            echo "<script>alert('Pesanan Sukses!'); window.location='sukses_pembayaran.php?id_pesanan=$id_pesanan';</script>";
            exit();
        } else {
            $error = "Gagal menyimpan pesanan: " . mysqli_error($conn);
        }
    }
}
?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <title>Checkout - Alfateeh Sepatuku</title>
    <style>
        body{background:#f5f5f5; font-family:'Poppins',sans-serif; padding:20px;}
        .checkout-container{max-width:700px; margin:0 auto; background:#fff; padding:25px; border-radius:12px; box-shadow:0 0 15px rgba(0,0,0,0.1);}
        input, select, textarea { width:100%; padding:10px; margin-top:5px; border:1px solid #ddd; border-radius:6px; box-sizing:border-box; }
        .submit-btn { background:#00b4d8; color:#fff; border:none; width:100%; padding:15px; border-radius:8px; font-weight:bold; cursor:pointer; margin-top:20px; }
        .summary { background:#f9f9f9; padding:15px; border-radius:8px; margin-top:20px; border:1px dashed #1e88e5; }
    </style>
</head>
<body>

<div class="checkout-container">
    <h2 style="text-align:center; color:#1e88e5;">Konfirmasi Pengiriman</h2>
    
    <?php if($error): ?>
        <div style="background:#ffebee; color:#c62828; padding:10px; border-radius:6px; margin-bottom:15px;"><?= $error ?></div>
    <?php endif; ?>

    <form method="POST" enctype="multipart/form-data">
        <label>Nama Penerima</label>
        <input type="text" name="nama_penerima" required>

        <label>No. HP</label>
        <input type="text" name="no_hp" required>

        <label>Alamat Lengkap</label>
        <textarea name="alamat_lengkap" rows="3" required></textarea>

        <div style="display:flex; gap:10px;">
            <div style="flex:1;">
                <label>Provinsi</label>
                <select name="provinsi" id="provinsi" required>
                    <option value="">-- Pilih --</option>
                    <option value="Jawa Tengah">Jawa Tengah</option>
                    <option value="Jawa Barat">Jawa Barat</option>
                </select>
            </div>
            <div style="flex:1;">
                <label>Kota</label>
                <select name="kota" id="kota" required>
                    <option value="">-- Pilih Kota --</option>
                </select>
            </div>
        </div>

        <label>Kode Pos</label>
        <input type="text" name="kode_pos" required>

        <label>Ekspedisi</label>
        <select name="ekspedisi" required>
            <option value="JNE">JNE</option>
            <option value="J&T">J&T</option>
        </select>

        <label>Metode Pembayaran</label>
        <select name="metode_pembayaran" id="metode" onchange="toggleUpload()" required>
            <option value="">-- Pilih --</option>
            <option value="COD">COD</option>
            <option value="Transfer Bank">Transfer Bank</option>
        </select>

        <div id="upload_bukti" style="display:none;">
            <label>Upload Bukti Transfer</label>
            <input type="file" name="bukti_pembayaran" accept="image/*">
        </div>

        <div class="summary">
            <h4>Ringkasan Pesanan</h4>
            <?php 
            $total_belanja = 0;
            foreach($checkout_cart as $item): 
                $sql = mysqli_query($conn,"SELECT nama, harga FROM produk WHERE id='".$item['id_produk']."'");
                $p = mysqli_fetch_assoc($sql);
                $sub = $p['harga'] * $item['qty'];
                $total_belanja += $sub;
            ?>
            <div style="display:flex; justify-content:space-between; margin-bottom:5px;">
                <span><?= $p['nama'] ?> (Size: <?= $item['ukuran'] ?>) x <?= $item['qty'] ?></span>
                <span>Rp <?= number_format($sub,0,",",".") ?></span>
            </div>
            <?php endforeach; ?>
            <hr>
            <div style="display:flex; justify-content:space-between; font-weight:bold;">
                <span>Total + Ongkir (10k)</span>
                <span>Rp <?= number_format($total_belanja + 10000,0,",",".") ?></span>
            </div>
        </div>

        <button type="submit" name="checkout" class="submit-btn">KONFIRMASI PESANAN</button>
    </form>
</div>

<script>
    const dataKota = { "Jawa Tengah":["Semarang","Solo"], "Jawa Barat":["Bandung","Bogor"] };
    document.getElementById("provinsi").addEventListener("change", function(){
        const kota = document.getElementById("kota");
        kota.innerHTML = '<option value="">-- Pilih Kota --</option>';
        if(dataKota[this.value]) dataKota[this.value].forEach(k => {
            let op = new Option(k, k); kota.add(op);
        });
    });

    function toggleUpload(){
        document.getElementById("upload_bukti").style.display = 
            (document.getElementById("metode").value === 'Transfer Bank') ? "block" : "none";
    }
</script>
</body>
</html>