<?php
include 'koneksi.php';

if (!isset($_GET['order_id'])) {
    header("Location: ../Order/order.php?msg=parameter_kurang");
    exit;
}

$order_id = $_GET['order_id'];

$queryOrder = mysqli_query($conn, "SELECT * FROM orders WHERE order_id = '$order_id' AND order_type = 'membership'");
if (mysqli_num_rows($queryOrder) == 0) {
    header("Location: order_list.php?msg=order_tidak_valid");
    exit;
}

$order = mysqli_fetch_assoc($queryOrder);
$member_id = $order['member_id'];

$queryMembershipOrder = mysqli_query($conn, "SELECT * FROM membersip_order WHERE order_id = '$order_id'");
if (mysqli_num_rows($queryMembershipOrder) == 0) {
    header("Location: ../Order/order.php?msg=data_membership_order_tidak_ada");
    exit;
}

$membershipOrder = mysqli_fetch_assoc($queryMembershipOrder);
$package_id = $membershipOrder['membership_id'];

$queryPackage = mysqli_query($conn, "SELECT * FROM membership_packages WHERE package_id = '$package_id'");
if (mysqli_num_rows($queryPackage) == 0) {
    header("Location: ../Order/order.php?msg=package_tidak_valid");
    exit;
}

$package = mysqli_fetch_assoc($queryPackage);

$tanggal_mulai = date('Y-m-d');

$durasi_raw = strtolower($package['duration']);
$durasi_parts = explode(' ', $durasi_raw);

if (count($durasi_parts) !== 2) {
    header("Location: ../Order/order.php?msg=format_durasi_tidak_valid");
    exit;
}

$jumlah = (int)$durasi_parts[0];
$satuan = $durasi_parts[1];

if ($jumlah <= 0) {
    header("Location: ../Order/order.php?msg=durasi_angka_tidak_valid");
    exit;
}

switch ($satuan) {
    case 'hari':
        $tanggal_berakhir = date('Y-m-d', strtotime("+$jumlah days"));
        break;
    case 'bulan':
        $tanggal_berakhir = date('Y-m-d', strtotime("+$jumlah months"));
        break;
    case 'tahun':
        $tanggal_berakhir = date('Y-m-d', strtotime("+$jumlah years"));
        break;
    default:
        header("Location: ../Order/order.php?msg=satuan_durasi_tidak_valid");
        exit;
}

$harga_dibayar = $order['total_harga'];
$created_at = date('Y-m-d H:i:s');

$queryInsert = mysqli_query($conn, "INSERT INTO member_subscriptions (member_id, package_id, tanggal_mulai, tanggal_berakhir, harga_dibayar, status_langganan, created_at) VALUES ('$member_id', '$package_id', '$tanggal_mulai', '$tanggal_berakhir', '$harga_dibayar', 'aktif', '$created_at')");

if ($queryInsert) {
    mysqli_query($conn, "UPDATE orders SET status = 'Selesai' WHERE order_id = '$order_id'");
    header("Location: ../Order/order.php?msg=aktivasi_sukses");
} else {
    header("Location: ../Order/order.php?msg=aktivasi_gagal");
}
?>
