<?php
session_start();
if (!isset($_SESSION['user'])) {
    header('Location: ../login');
    exit();
}

include('../../config/koneksi.php');

// Pastikan folder uploads ada
$upload_dir = "../../uploads/";
if (!is_dir($upload_dir)) {
    mkdir($upload_dir, 0777, true);
}

// Ambil data file
$filename = $_FILES["file"]["name"];
$file_basename = pathinfo($filename, PATHINFO_FILENAME); // Ambil nama file tanpa ekstensi
$file_ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION)); // Ambil ekstensi file dalam huruf kecil
$filesize = $_FILES["file"]["size"];
$allowed_file_types = ['jpg', 'png', 'jpeg', 'gif']; // Pastikan ekstensi tidak ada spasi

if (in_array($file_ext, $allowed_file_types) && $filesize < 5048000) {
    // Ubah nama file menjadi hash untuk menghindari duplikasi
    $newfilename = md5($file_basename . time()) . '.' . $file_ext;

    if (file_exists($upload_dir . $newfilename)) {
        echo "<script>alert('File sudah ada!'); window.location.href='../pelatih/create.php';</script>";
    } else {
        if (move_uploaded_file($_FILES["file"]["tmp_name"], $upload_dir . $newfilename)) {
            // Ambil data dari form dan sanitasi
            $foto_pelatih = $newfilename;
            $nama_pelatih = mysqli_real_escape_string($db, htmlspecialchars($_POST['nama_pelatih']));
            $alamat = mysqli_real_escape_string($db, htmlspecialchars($_POST['alamat']));
            $asal_ranting = mysqli_real_escape_string($db, htmlspecialchars($_POST['asal_ranting']));
            $id_user = $_SESSION['user']['id_user'];

            // Gunakan prepared statement untuk mencegah SQL injection
            $query = "INSERT INTO `pelatih` (`foto_pelatih`, `nama_pelatih`, `alamat`, `asal_ranting`, `id_user`, `created_at`, `updated_at`) 
                      VALUES (?, ?, ?, ?, ?, CURRENT_TIMESTAMP, '0000-00-00 00:00:00')";

            $stmt = mysqli_prepare($db, $query);
            mysqli_stmt_bind_param($stmt, "ssssi", $foto_pelatih, $nama_pelatih, $alamat, $asal_ranting, $id_user);
            $hasil = mysqli_stmt_execute($stmt);

            if ($hasil) {
                echo "<script>alert('Tambah pelatih berhasil'); window.location.href='../pelatih';</script>";
            } else {
                echo "<script>alert('Tambah pelatih gagal!'); window.location.href='../pelatih';</script>";
            }
            mysqli_stmt_close($stmt);
        } else {
            echo "<script>alert('Gagal mengunggah file!'); window.location.href='../pelatih/create.php';</script>";
        }
    }
} elseif (empty($filename)) {
    echo "<script>alert('Pilih file untuk diunggah'); window.location.href='../pelatih/create.php';</script>";
} elseif ($filesize > 5048000) {
    echo "<script>alert('File yang diunggah terlalu besar!'); window.location.href='../pelatih/create.php';</script>";
} else {
    echo "<script>alert('Format file salah'); window.location.href='../pelatih/create.php';</script>";
}
?>
