<?php
// add_product.php - Handle product submission with secure image upload (Admin Only)
session_start();
require_once 'db.php';

// Access Control check
if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'admin') {
    header("Location: login.php");
    exit();
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = isset($_POST['name']) ? trim($_POST['name']) : '';
    $description = isset($_POST['description']) ? trim($_POST['description']) : '';
    $price = isset($_POST['price']) ? floatval($_POST['price']) : 0.0;
    $category = isset($_POST['category']) ? trim($_POST['category']) : '';
    $sizes = isset($_POST['sizes']) ? trim($_POST['sizes']) : '';
    $colors = isset($_POST['colors']) ? trim($_POST['colors']) : '';
    $stock = isset($_POST['stock']) ? intval($_POST['stock']) : 0;

    // Check basic parameters
    if ($name === '' || $price <= 0 || $category === '' || !isset($_FILES['image'])) {
        header("Location: admin.php?tab=products&error_msg=" . urlencode("กรุณากรอกข้อมูลที่จำเป็นให้ครบถ้วน"));
        exit();
    }

    // Image Upload Handling
    $file = $_FILES['image'];
    if ($file['error'] !== UPLOAD_ERR_OK) {
        header("Location: admin.php?tab=products&error_msg=" . urlencode("เกิดข้อผิดพลาดในการอัปโหลดรูปภาพ (Error Code: " . $file['error'] . ")"));
        exit();
    }

    // Validate size (Limit to 5MB)
    $max_size = 5 * 1024 * 1024;
    if ($file['size'] > $max_size) {
        header("Location: admin.php?tab=products&error_msg=" . urlencode("ขนาดไฟล์รูปภาพห้ามเกิน 5MB"));
        exit();
    }

    // Validate extension
    $allowed_extensions = ['jpg', 'jpeg', 'png'];
    $file_info = pathinfo($file['name']);
    $extension = isset($file_info['extension']) ? strtolower($file_info['extension']) : '';

    if (!in_array($extension, $allowed_extensions)) {
        header("Location: admin.php?tab=products&error_msg=" . urlencode("อนุญาตให้อัปโหลดเฉพาะไฟล์รูปภาพ .jpg, .jpeg, .png เท่านั้น"));
        exit();
    }

    // Double check MIME type for safety
    $finfo = finfo_open(FILEINFO_MIME_TYPE);
    $mime_type = finfo_file($finfo, $file['tmp_name']);
    finfo_close($finfo);

    $allowed_mimes = ['image/jpeg', 'image/png', 'image/pjpeg', 'image/x-png'];
    if (!in_array($mime_type, $allowed_mimes)) {
        header("Location: admin.php?tab=products&error_msg=" . urlencode("ประเภทของไฟล์รูปภาพไม่ถูกต้อง"));
        exit();
    }

    // Setup Upload Directory
    $upload_dir = __DIR__ . '/images';
    if (!is_dir($upload_dir)) {
        mkdir($upload_dir, 0777, true);
    }

    // Randomize filename to prevent collisions and security threats
    $new_filename = time() . '_' . bin2hex(random_bytes(4)) . '.' . $extension;
    $target_filepath = $upload_dir . '/' . $new_filename;

    if (move_uploaded_file($file['tmp_name'], $target_filepath)) {
        $db_image_path = 'images/' . $new_filename;
        
        try {
            // Save product to database using Prepared Statement (SQL Injection Prevention)
            $stmt = $pdo->prepare("
                INSERT INTO products (name, description, price, category, sizes, colors, stock, image) 
                VALUES (:name, :description, :price, :category, :sizes, :colors, :stock, :image)
            ");
            
            $stmt->execute([
                ':name' => $name,
                ':description' => $description,
                ':price' => $price,
                ':category' => $category,
                ':sizes' => $sizes,
                ':colors' => $colors,
                ':stock' => $stock,
                ':image' => $db_image_path
            ]);

            header("Location: admin.php?tab=products&success_msg=" . urlencode("เพิ่มสินค้าและอัปโหลดรูปภาพสำเร็จแล้ว"));
            exit();

        } catch (Exception $e) {
            // If DB insert fails, remove the uploaded file to keep filesystem clean
            @unlink($target_filepath);
            header("Location: admin.php?tab=products&error_msg=" . urlencode("เกิดข้อผิดพลาดในการบันทึกข้อมูล: " . $e->getMessage()));
            exit();
        }
    } else {
        header("Location: admin.php?tab=products&error_msg=" . urlencode("ล้มเหลวในการจัดเก็บไฟล์ในระบบเซิร์ฟเวอร์"));
        exit();
    }
} else {
    header("Location: admin.php");
    exit();
}
?>
