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

if (!isset($_SESSION['admin_id'])) {
    header("Location: index");
    exit();
}

if (!isset($_GET['id'])) {
    $_SESSION['error'] = "ID anggota tim tidak valid";
    header("Location: tim");
    exit();
}

$id = (int)$_GET['id'];
// Path relatif ke folder upload
$upload_dir = '../upload/tim/';
$base_url = 'http://' . $_SERVER['HTTP_HOST'] . '/upload/tim/'; // Sesuaikan path domain

// Get team member ID dari URL
$team_member_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

// Ambil data anggota tim
$stmt = $pdo->prepare("SELECT * FROM team_members WHERE id = ?");
$stmt->execute([$team_member_id]);
$team_member = $stmt->fetch();

if ($team_member) {
    try {
        $pdo->beginTransaction();

        // Hapus gambar fisik
        if (!empty($team_member['gambar'])) {
            $old_image_path = str_replace($base_url, $upload_dir, $team_member['gambar']);
            if (file_exists($old_image_path)) {
                unlink($old_image_path);
            }
        }

        // Hapus dari database
        $stmt = $pdo->prepare("DELETE FROM team_members WHERE id = ?");
        $stmt->execute([$team_member_id]);

        $pdo->commit();

        $_SESSION['success'] = "Anggota tim berhasil dihapus!";
    } catch (Exception $e) {
        $pdo->rollBack();
        $_SESSION['error'] = "Gagal menghapus anggota tim: " . $e->getMessage();
    }
}

header("Location: tim");
exit();
