<?php
header("Content-Type: application/json; charset=UTF-8");

require 'security.php';
require 'logger.php';
require 'db.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['error' => 'Method Not Allowed']);
    log_activity("Method Not Allowed on addproduk.php from IP: " . $_SERVER['REMOTE_ADDR']);
    exit;
}

// Mendapatkan token dari header Authorization
$headers = apache_request_headers();
if (isset($headers['Authorization'])) {
    $authorizationHeader = $headers['Authorization'];
    $token = str_replace("Bearer ", "", $authorizationHeader);
} else {
    http_response_code(401);
    echo json_encode(['error' => 'Authorization header missing']);
    log_activity("Authorization header missing in addproduk.php");
    exit;
}

try {
    // 1) Cari user_id berdasarkan token
    $stmt = $pdo->prepare("SELECT user_id FROM tokens WHERE token = ? AND expires_at >= NOW()");
    $stmt->execute([$token]);
    $tokenData = $stmt->fetch();

    if (!$tokenData) {
        http_response_code(401);
        echo json_encode(['error' => 'Invalid or expired token']);
        log_activity("Invalid or expired token in addproduk.php");
        exit;
    }

    $userId = $tokenData['user_id'];

    // 2) Mengambil data produk dari form-data
    $inputData = $_POST; // Menggunakan $_POST karena data dikirim sebagai form-data

    // Validasi input
    if (empty($inputData['judul']) || empty($inputData['harga']) || empty($inputData['kuantitas']) || empty($inputData['kategori_id'])) {
        http_response_code(400);
        echo json_encode(['error' => 'All fields are required']);
        log_activity("Missing required fields in addproduk.php");
        exit;
    }

    $judul = $inputData['judul'];
    $harga = $inputData['harga'];
    $kuantitas = $inputData['kuantitas'];
    $diskon = isset($inputData['diskon']) ? $inputData['diskon'] : 0;
    $catatan = isset($inputData['catatan']) ? $inputData['catatan'] : '';
    $kategoriId = $inputData['kategori_id'];

    // 3) Mengolah gambar (jika ada)
    $pathGambar = null;
    if (isset($_FILES['gambar']) && $_FILES['gambar']['error'] === UPLOAD_ERR_OK) {
        // Validasi ukuran file (maksimal 2MB)
        if ($_FILES['gambar']['size'] > 2 * 1024 * 1024) {
            http_response_code(400);
            echo json_encode(['error' => 'File size exceeds the 2MB limit']);
            log_activity("File size exceeds 2MB in addproduk.php");
            exit;
        }

        // Validasi ekstensi file (hanya gambar yang diperbolehkan)
        $allowedExtensions = ['jpg', 'jpeg', 'png'];
        $fileExtension = strtolower(pathinfo($_FILES['gambar']['name'], PATHINFO_EXTENSION));

        if (!in_array($fileExtension, $allowedExtensions)) {
            http_response_code(400);
            echo json_encode(['error' => 'Only JPG, JPEG, and PNG files are allowed']);
            log_activity("Invalid file type in addproduk.php");
            exit;
        }

        // Validasi MIME type file (pastikan file benar-benar gambar)
        $fileMimeType = mime_content_type($_FILES['gambar']['tmp_name']);
        $allowedMimeTypes = ['image/jpeg', 'image/png'];

        if (!in_array($fileMimeType, $allowedMimeTypes)) {
            http_response_code(400);
            echo json_encode(['error' => 'Invalid file type. Only images are allowed']);
            log_activity("Invalid MIME type in addproduk.php");
            exit;
        }

        // Menyimpan gambar ke folder "uploads/"
        $uploadDir = 'uploads/';
        $randomString = bin2hex(random_bytes(8)); // Menambahkan random string ke nama file
        $fileName = 'produk_' . $randomString . '_' . uniqid('', true) . '.' . $fileExtension;
        $filePath = $uploadDir . $fileName;

        if (move_uploaded_file($_FILES['gambar']['tmp_name'], $filePath)) {
            // Tambahkan base URL ke path gambar
            $baseUrl = "https://kopmandan.com/api/";
            $pathGambar = $baseUrl . $filePath; // Lengkapi dengan base URL
        } else {
            http_response_code(500);
            echo json_encode(['error' => 'Failed to upload the image']);
            log_activity("Failed to upload image in addproduk.php");
            exit;
        }
    }

    // 4) Menyimpan produk baru ke database
    $sql = "
        INSERT INTO produk (judul, harga, kuantitas, diskon, catatan, kategori_id, id_penjual, path_gambar)
        VALUES (:judul, :harga, :kuantitas, :diskon, :catatan, :kategori_id, :id_penjual, :path_gambar)
    ";

    $stmt = $pdo->prepare($sql);
    $stmt->bindValue(':judul', $judul, PDO::PARAM_STR);
    $stmt->bindValue(':harga', $harga, PDO::PARAM_INT);
    $stmt->bindValue(':kuantitas', $kuantitas, PDO::PARAM_INT);
    $stmt->bindValue(':diskon', $diskon, PDO::PARAM_INT);
    $stmt->bindValue(':catatan', $catatan, PDO::PARAM_STR);
    $stmt->bindValue(':kategori_id', $kategoriId, PDO::PARAM_INT);
    $stmt->bindValue(':id_penjual', $userId, PDO::PARAM_INT);
    $stmt->bindValue(':path_gambar', $pathGambar, PDO::PARAM_STR);

    $stmt->execute();

    // 5) Mendapatkan ID produk yang baru ditambahkan
    $produkId = $pdo->lastInsertId();

    // 6) Response sukses
    http_response_code(201);
    echo json_encode([
        'message' => 'Produk berhasil ditambahkan'
    ]);
    log_activity("Produk ID $produkId added by user $userId.");

} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['error' => 'Server error', 'message' => $e->getMessage()]);
    log_activity("addproduk.php error: " . $e->getMessage());
    exit;
}
?>