<?php
require_once $_SERVER['DOCUMENT_ROOT'] . '/yoga/includes/config.php';
require_once $_SERVER['DOCUMENT_ROOT'] . '/yoga/includes/functions.php';

// Cek login
cek_login();

// Cek akses
if (!cek_akses('penggajian', 'delete')) {
    header("Location: " . BASE_URL . "/index.php?access=denied");
    exit();
}

// Cek ID
if (!isset($_GET['id']) || empty($_GET['id'])) {
    header("Location: " . BASE_URL . "/modules/penggajian/index.php?error=" . urlencode("ID penggajian tidak valid!"));
    exit();
}

$id = (int)$_GET['id'];

// Ambil data penggajian
$query = "SELECT * FROM penggajian WHERE id = $id";
$result = mysqli_query($conn, $query);

if (mysqli_num_rows($result) == 0) {
    header("Location: " . BASE_URL . "/modules/penggajian/index.php?error=" . urlencode("Data penggajian tidak ditemukan!"));
    exit();
}

$penggajian = mysqli_fetch_assoc($result);

// Cek status penggajian
if ($penggajian['status'] == 'dibayar') {
    header("Location: " . BASE_URL . "/modules/penggajian/index.php?error=" . urlencode("Data penggajian yang sudah dibayar tidak dapat dihapus!"));
    exit();
}

// Simpan data periode untuk redirect
$bulan = $penggajian['periode_bulan'];
$tahun = $penggajian['periode_tahun'];

// Begin transaction
mysqli_begin_transaction($conn);

try {
    // Hapus detail potongan terlebih dahulu
    $delete_detail = "DELETE FROM detail_potongan WHERE penggajian_id = $id";
    mysqli_query($conn, $delete_detail);
    
    // Hapus data penggajian
    $delete_query = "DELETE FROM penggajian WHERE id = $id";
    
    if (mysqli_query($conn, $delete_query)) {
        // Commit transaction
        mysqli_commit($conn);
        
        header("Location: " . BASE_URL . "/modules/penggajian/index.php?bulan=$bulan&tahun=$tahun&success=" . urlencode("Data penggajian berhasil dihapus!"));
        exit();
    } else {
        throw new Exception("Gagal menghapus data penggajian!");
    }
} catch (Exception $e) {
    // Rollback transaction
    mysqli_rollback($conn);
    
    header("Location: " . BASE_URL . "/modules/penggajian/index.php?bulan=$bulan&tahun=$tahun&error=" . urlencode("Gagal menghapus data penggajian: " . $e->getMessage()));
    exit();
}
?>