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

// Inklusi file keamanan dan autentikasi
require 'security.php';
require 'logger.php';
require 'rate_limit.php';
require 'authenticate.php';

// Cek metode request
$method = $_SERVER['REQUEST_METHOD'];
$allowed_methods = ['GET', 'POST', 'PUT', 'DELETE'];
if (!in_array($method, $allowed_methods)) {
    http_response_code(405);
    echo json_encode(['error' => 'Method Not Allowed']);
    log_activity("Method Not Allowed on master_manage_icons.php from IP: " . $_SERVER['REMOTE_ADDR']);
    exit;
}

// Autentikasi: Hanya master_admin yang diizinkan
$user = authenticate($pdo, ['master_admin']);

// Terapkan rate limiting spesifik endpoint jika diperlukan
$identifier = $_SERVER['REMOTE_ADDR'] . ':' . $_SERVER['REQUEST_URI'];
rate_limit($pdo, 100, 60, $identifier);

// Mengambil ID ikon dari URL jika ada
$icon_id = null;
if (isset($_GET['id'])) {
    $icon_id = intval($_GET['id']);
}

// Handle setiap metode
switch ($method) {
    case 'GET':
        if ($icon_id) {
            // Ambil satu ikon
            try {
                $stmt = $pdo->prepare("SELECT * FROM icons WHERE id = ?");
                $stmt->execute([$icon_id]);
                $icon = $stmt->fetch();

                if (!$icon) {
                    http_response_code(404);
                    echo json_encode(['error' => 'Icon not found']);
                    log_activity("Icon ID $icon_id not found.");
                    exit;
                }

                http_response_code(200);
                echo json_encode(['icon' => $icon]);
                log_activity("Icon ID $icon_id retrieved by user_id: " . $user['id']);

            } catch (Exception $e) {
                http_response_code(500);
                echo json_encode(['error' => 'Server error']);
                log_activity("master_manage_icons.php GET error: " . $e->getMessage());
                exit;
            }
        } else {
            // Ambil semua ikon
            try {
                $stmt = $pdo->prepare("SELECT * FROM icons");
                $stmt->execute();
                $icons = $stmt->fetchAll();

                http_response_code(200);
                echo json_encode(['icons' => $icons]);
                log_activity("All icons retrieved by user_id: " . $user['id']);

            } catch (Exception $e) {
                http_response_code(500);
                echo json_encode(['error' => 'Server error']);
                log_activity("master_manage_icons.php GET all error: " . $e->getMessage());
                exit;
            }
        }
        break;

    case 'POST':
        // Tambah ikon baru
        // Untuk upload file, gunakan multipart/form-data
        if (!isset($_FILES['icon_file'])) {
            http_response_code(400);
            echo json_encode(['error' => 'Icon file is required']);
            log_activity("Icon file missing in POST request.");
            exit;
        }

        // Sanitasi input
        $type = isset($_POST['type']) ? sanitize_input($_POST['type']) : null;
        $name = isset($_POST['name']) ? sanitize_input($_POST['name']) : null;

        // Validasi input
        if (empty($type) || empty($name)) {
            http_response_code(400);
            echo json_encode(['error' => 'Type and name are required']);
            log_activity("Type and/or name missing in POST request.");
            exit;
        }

        $valid_types = ['application', 'category', 'menu', 'button'];
        if (!in_array($type, $valid_types)) {
            http_response_code(400);
            echo json_encode(['error' => 'Invalid icon type']);
            log_activity("Invalid icon type '$type' in POST request.");
            exit;
        }

        // Validasi file
        $allowed_extensions = ['png', 'jpg', 'jpeg', 'svg', 'ico'];
        $file_name = $_FILES['icon_file']['name'];
        $file_tmp = $_FILES['icon_file']['tmp_name'];
        $file_size = $_FILES['icon_file']['size'];
        $file_error = $_FILES['icon_file']['error'];

        if ($file_error !== UPLOAD_ERR_OK) {
            http_response_code(400);
            echo json_encode(['error' => 'Error uploading file']);
            log_activity("File upload error in POST request.");
            exit;
        }

        // Cek ekstensi file
        $file_ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
        if (!in_array($file_ext, $allowed_extensions)) {
            http_response_code(400);
            echo json_encode(['error' => 'Invalid file type']);
            log_activity("Invalid file type '$file_ext' in POST request.");
            exit;
        }

        // Cek ukuran file (maksimal 2MB)
        if ($file_size > 2 * 1024 * 1024) {
            http_response_code(400);
            echo json_encode(['error' => 'File size exceeds 2MB']);
            log_activity("File size exceeds limit in POST request.");
            exit;
        }

        // Tentukan path penyimpanan
        $upload_dir = __DIR__ . '/../uploads/icons/';
        if (!is_dir($upload_dir)) {
            if (!mkdir($upload_dir, 0755, true)) {
                http_response_code(500);
                echo json_encode(['error' => 'Server configuration error']);
                log_activity("Failed to create upload directory.");
                exit;
            }
        }

        // Buat nama file unik
        $unique_name = uniqid('icon_', true) . '.' . $file_ext;
        $file_path = 'uploads/icons/' . $unique_name;

        // Pindahkan file ke direktori tujuan
        if (!move_uploaded_file($file_tmp, $upload_dir . $unique_name)) {
            http_response_code(500);
            echo json_encode(['error' => 'Failed to move uploaded file']);
            log_activity("Failed to move uploaded file.");
            exit;
        }

        // Simpan data ikon ke database
        try {
            $stmt = $pdo->prepare("INSERT INTO icons (type, name, file_path) VALUES (?, ?, ?)");
            $stmt->execute([$type, $name, $file_path]);

            http_response_code(201);
            echo json_encode(['message' => 'Icon created successfully', 'icon_id' => $pdo->lastInsertId()]);
            log_activity("Icon '$name' created by user_id: " . $user['id']);

        } catch (Exception $e) {
            // Hapus file yang diupload jika gagal menyimpan ke database
            unlink($upload_dir . $unique_name);
            http_response_code(500);
            echo json_encode(['error' => 'Server error']);
            log_activity("master_manage_icons.php POST error: " . $e->getMessage());
            exit;
        }
        break;

    case 'PUT':
        // Update ikon
        if (!$icon_id) {
            http_response_code(400);
            echo json_encode(['error' => 'Icon ID is required']);
            log_activity("Icon ID missing in PUT request.");
            exit;
        }

        // Parsing input untuk metode PUT
        // Karena PHP tidak secara otomatis menangani multipart/form-data untuk PUT, Anda perlu menggunakan workaround
        // Namun, untuk kesederhanaan, kami anggap bahwa update file dilakukan melalui POST dengan parameter tambahan

        // **Catatan:** Implementasi upload file pada metode PUT di PHP memerlukan handling yang lebih kompleks dan biasanya dilakukan melalui POST dengan parameter tambahan.

        // Di sini, kita akan menggunakan pendekatan sederhana: hanya memperbarui nama ikon jika tidak ada file yang diupload
        // Jika ingin mengupload file baru, lebih baik menggunakan POST

        // Namun, untuk memenuhi permintaan, kita akan coba menangani file upload pada PUT

        // Ambil jenis konten
        $content_type = isset($_SERVER['CONTENT_TYPE']) ? $_SERVER['CONTENT_TYPE'] : '';

        if (strpos($content_type, 'multipart/form-data') !== false) {
            // Parsing multipart/form-data pada PUT
            parse_str(file_get_contents("php://input"), $_PUT);
            $_FILES = $_FILES; // Tidak ada cara langsung untuk mengisi $_FILES pada PUT
            // Karena keterbatasan PHP, sebaiknya gunakan POST untuk upload file
            // Untuk PUT, kita hanya akan memperbarui data tekstual
        }

        // Ambil parameter lain dari input
        $type = isset($_POST['type']) ? sanitize_input($_POST['type']) : null;
        $name = isset($_POST['name']) ? sanitize_input($_POST['name']) : null;

        // Sanitasi dan validasi input
        $fields = [];
        $params = [];

        if ($type) {
            $valid_types = ['application', 'category', 'menu', 'button'];
            if (!in_array($type, $valid_types)) {
                http_response_code(400);
                echo json_encode(['error' => 'Invalid icon type']);
                log_activity("Invalid icon type '$type' in PUT request.");
                exit;
            }
            $fields[] = "type = ?";
            $params[] = $type;
        }

        if ($name) {
            $fields[] = "name = ?";
            $params[] = $name;
        }

        // Cek apakah ada file yang diupload
        $icon_file_uploaded = false;
        if (isset($_FILES['icon_file']) && $_FILES['icon_file']['error'] === UPLOAD_ERR_OK) {
            $icon_file_uploaded = true;
            $file = $_FILES['icon_file'];

            // Validasi file
            $allowed_extensions = ['png', 'jpg', 'jpeg', 'svg', 'ico'];
            $file_name = $file['name'];
            $file_tmp = $file['tmp_name'];
            $file_size = $file['size'];
            $file_error = $file['error'];

            // Cek ekstensi file
            $file_ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
            if (!in_array($file_ext, $allowed_extensions)) {
                http_response_code(400);
                echo json_encode(['error' => 'Invalid file type']);
                log_activity("Invalid file type '$file_ext' in PUT request.");
                exit;
            }

            // Cek ukuran file (maksimal 2MB)
            if ($file_size > 2 * 1024 * 1024) {
                http_response_code(400);
                echo json_encode(['error' => 'File size exceeds 2MB']);
                log_activity("File size exceeds limit in PUT request.");
                exit;
            }

            // Tentukan path penyimpanan
            $upload_dir = __DIR__ . '/../uploads/icons/';
            if (!is_dir($upload_dir)) {
                if (!mkdir($upload_dir, 0755, true)) {
                    http_response_code(500);
                    echo json_encode(['error' => 'Server configuration error']);
                    log_activity("Failed to create upload directory in PUT request.");
                    exit;
                }
            }

            // Buat nama file unik
            $unique_name = uniqid('icon_', true) . '.' . $file_ext;
            $new_file_path = 'uploads/icons/' . $unique_name;

            // Pindahkan file ke direktori tujuan
            if (!move_uploaded_file($file_tmp, $upload_dir . $unique_name)) {
                http_response_code(500);
                echo json_encode(['error' => 'Failed to move uploaded file']);
                log_activity("Failed to move uploaded file in PUT request.");
                exit;
            }

            // Tambahkan file_path ke fields
            $fields[] = "file_path = ?";
            $params[] = $new_file_path;
        }

        if (empty($fields)) {
            http_response_code(400);
            echo json_encode(['error' => 'No fields to update']);
            log_activity("No fields to update in PUT request for Icon ID $icon_id.");
            exit;
        }

        $params[] = $icon_id;

        try {
            // Ambil data ikon lama jika ada file baru diupload
            if ($icon_file_uploaded) {
                $stmt = $pdo->prepare("SELECT file_path FROM icons WHERE id = ?");
                $stmt->execute([$icon_id]);
                $icon = $stmt->fetch();

                if ($icon) {
                    $old_file_path = __DIR__ . '/' . $icon['file_path'];
                    if (file_exists($old_file_path)) {
                        unlink($old_file_path);
                        log_activity("Old icon file '$icon['file_path']' deleted.");
                    }
                }
            }

            // Update data ikon
            $stmt = $pdo->prepare("UPDATE icons SET " . implode(', ', $fields) . " WHERE id = ?");
            $stmt->execute($params);

            http_response_code(200);
            echo json_encode(['message' => 'Icon updated successfully']);
            log_activity("Icon ID $icon_id updated by user_id: " . $user['id']);

        } catch (Exception $e) {
            // Hapus file yang diupload jika gagal menyimpan ke database
            if ($icon_file_uploaded) {
                unlink($upload_dir . $unique_name);
                log_activity("Uploaded file '$new_file_path' deleted due to server error.");
            }
            http_response_code(500);
            echo json_encode(['error' => 'Server error']);
            log_activity("master_manage_icons.php PUT error: " . $e->getMessage());
            exit;
        }
        break;

    case 'DELETE':
        // Hapus ikon
        if (!$icon_id) {
            http_response_code(400);
            echo json_encode(['error' => 'Icon ID is required']);
            log_activity("Icon ID missing in DELETE request.");
            exit;
        }

        try {
            // Ambil path file ikon
            $stmt = $pdo->prepare("SELECT file_path FROM icons WHERE id = ?");
            $stmt->execute([$icon_id]);
            $icon = $stmt->fetch();

            if (!$icon) {
                http_response_code(404);
                echo json_encode(['error' => 'Icon not found']);
                log_activity("Icon ID $icon_id not found in DELETE request.");
                exit;
            }

            $file_path = __DIR__ . '/' . $icon['file_path'];
            if (file_exists($file_path)) {
                unlink($file_path);
                log_activity("Icon file '$icon['file_path']' deleted.");
            }

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

            http_response_code(200);
            echo json_encode(['message' => 'Icon deleted successfully']);
            log_activity("Icon ID $icon_id deleted by user_id: " . $user['id']);

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

    default:
        http_response_code(405);
        echo json_encode(['error' => 'Method Not Allowed']);
        log_activity("Method Not Allowed on master_manage_icons.php from IP: " . $_SERVER['REMOTE_ADDR']);
        exit;
}
?>
