<?php
include "../../config/connect.php";

if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_FILES['gambar'])) {
    $targetDir = "profile/";
    $targetFile = $targetDir . basename($_FILES["gambar"]["name"]);
    $uploadOk = 1;
    $imageFileType = strtolower(pathinfo($targetFile, PATHINFO_EXTENSION));

    // Cek apakah gambar sebenarnya
    $check = getimagesize($_FILES["gambar"]["tmp_name"]);
    if ($check === false) {
        echo json_encode(["status" => "error", "message" => "File bukan gambar."]);
        $uploadOk = 0;
    }

    // Cek ukuran file (maks 5MB)
    if ($_FILES["gambar"]["size"] > 5000000) {
        echo json_encode(["status" => "error", "message" => "Ukuran file terlalu besar."]);
        $uploadOk = 0;
    }

    // Izinkan format tertentu
    if (!in_array($imageFileType, ['jpg', 'jpeg', 'png', 'gif'])) {
        echo json_encode(["status" => "error", "message" => "Hanya file JPG, JPEG, PNG & GIF yang diizinkan."]);
        $uploadOk = 0;
    }

    // Cek jika $uploadOk diset ke 0 karena ada kesalahan
    if ($uploadOk == 0) {
        echo json_encode(["status" => "error", "message" => "Gambar tidak di-upload."]);
    } else {
        if (move_uploaded_file($_FILES["gambar"]["tmp_name"], $targetFile)) {
            // Simpan informasi ke database
            $stmt = $conn->prepare("UPDATE agen_voucher SET profile = :profile WHERE id = :id");
            $stmt->bindParam(':profile', basename($_FILES["gambar"]["name"]), PDO::PARAM_STR);
            $stmt->bindParam(':id', $_SESSION['agen']);
            $stmt->execute();
            $stmt->close();
            echo json_encode(["status" => "success", "message" => "File telah di-upload."]);
        } else {
            echo json_encode(["status" => "error", "message" => "Terjadi kesalahan saat meng-upload gambar."]);
        }
    }
}
?>
