<?php
require '../config.php';
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

// Hapus pengecekan session admin agar bisa update status tanpa login

// Validasi input POST
if (!isset($_POST['id']) || !isset($_POST['status'])) {
    header("Location: ../admin/cek_pesanan.php?error=missing_data");
    exit;
}

$id = (int)$_POST['id'];
$status = $_POST['status'];
$resi = trim($_POST['resi'] ?? '');

// Validasi ID transaksi
if ($id <= 0) {
    header("Location: ../admin/cek_pesanan.php?error=invalid_id");
    exit;
}

// Validasi status
$valid_status = ['menunggu', 'dibayar', 'dikirim', 'selesai', 'dibatalkan'];
if (!in_array($status, $valid_status)) {
    header("Location: ../admin/cek_pesanan.php?error=status_invalid");
    exit;
}

// Cek apakah transaksi exist
$check_query = "SELECT id FROM transaksi WHERE id = ?";
$check_stmt = $conn->prepare($check_query);
$check_stmt->bind_param("i", $id);
$check_stmt->execute();
$check_result = $check_stmt->get_result();

if ($check_result->num_rows === 0) {
    header("Location: ../admin/cek_pesanan.php?error=transaksi_not_found");
    exit;
}

// Jika status dikirim, wajib ada resi
if ($status === 'dikirim') {
    if ($resi === '') {
        header("Location: ../admin/cek_pesanan.php?error=resi_kosong");
        exit;
    }

    // Simpan dengan resi dan update diubah_pada
    $update_query = "UPDATE transaksi SET status = ?, resi = ?, diubah_pada = NOW() WHERE id = ?";
    $stmt = $conn->prepare($update_query);
    $stmt->bind_param("ssi", $status, $resi, $id);
} else {
    // Selain dikirim, resi tidak boleh diisi, tetap update diubah_pada
    $update_query = "UPDATE transaksi SET status = ?, resi = NULL, diubah_pada = NOW() WHERE id = ?";
    $stmt = $conn->prepare($update_query);
    $stmt->bind_param("si", $status, $id);
}

// Execute update
if ($stmt->execute()) {
    header("Location: ../admin/cek_pesanan.php?success=1");
} else {
    header("Location: ../admin/cek_pesanan.php?error=update_failed");
}
exit;
