<?php
require_once '../connection.php';

// Check if user is admin
if (!isAdmin()) {
    header('Location: ../login.php');
    exit();
}

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    try {
        $pdo->beginTransaction();
        
        // Insert laptop data
        $stmt = $pdo->prepare("
            INSERT INTO laptops (
                category_id, brand, model, processor, ram, storage, display, 
                graphics, battery, os, warranty, condition, price, discount_price, 
                stock_quantity, is_featured, is_active, description
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
        ");
        
        $stmt->execute([
            $_POST['category_id'],
            $_POST['brand'],
            $_POST['model'],
            $_POST['processor'],
            $_POST['ram'],
            $_POST['storage'],
            $_POST['display'],
            $_POST['graphics'],
            $_POST['battery'],
            $_POST['os'],
            $_POST['warranty'],
            $_POST['condition'],
            $_POST['price'],
            $_POST['discount_price'] ?: null,
            $_POST['stock_quantity'],
            $_POST['is_featured'],
            $_POST['is_active'],
            $_POST['description']
        ]);
        
        $laptop_id = $pdo->lastInsertId();
        
        // Create upload directory if not exists
        $upload_dir = '../assets/images/laptops/';
        if (!file_exists($upload_dir)) {
            mkdir($upload_dir, 0777, true);
        }
        
        // Handle primary image
        if (isset($_FILES['primary_image']) && $_FILES['primary_image']['error'] == 0) {
            $primary_image = uploadImage($_FILES['primary_image'], $upload_dir, $laptop_id, 'primary');
            
            $stmt = $pdo->prepare("INSERT INTO laptop_images (laptop_id, image_url, is_primary, sort_order) VALUES (?, ?, 1, 1)");
            $stmt->execute([$laptop_id, $primary_image]);
        }
        
        // Handle additional images
        if (isset($_FILES['additional_images']) && !empty($_FILES['additional_images']['name'][0])) {
            $sort_order = 2;
            foreach ($_FILES['additional_images']['tmp_name'] as $key => $tmp_name) {
                if ($_FILES['additional_images']['error'][$key] == 0) {
                    $file = [
                        'name' => $_FILES['additional_images']['name'][$key],
                        'tmp_name' => $tmp_name,
                        'type' => $_FILES['additional_images']['type'][$key],
                        'error' => $_FILES['additional_images']['error'][$key],
                        'size' => $_FILES['additional_images']['size'][$key]
                    ];
                    
                    $image_url = uploadImage($file, $upload_dir, $laptop_id, 'additional_' . $key);
                    
                    $stmt = $pdo->prepare("INSERT INTO laptop_images (laptop_id, image_url, is_primary, sort_order) VALUES (?, ?, 0, ?)");
                    $stmt->execute([$laptop_id, $image_url, $sort_order]);
                    $sort_order++;
                }
            }
        }
        
        $pdo->commit();
        $_SESSION['success'] = "Laptop added successfully!";
        
    } catch (Exception $e) {
        $pdo->rollBack();
        $_SESSION['error'] = "Error adding laptop: " . $e->getMessage();
    }
    
    header('Location: laptops.php');
    exit();
}

// Function to upload image
function uploadImage($file, $upload_dir, $laptop_id, $prefix) {
    $allowed_types = ['image/jpeg', 'image/png', 'image/jpg', 'image/webp'];
    $max_size = 5 * 1024 * 1024; // 5MB
    
    if (!in_array($file['type'], $allowed_types)) {
        throw new Exception("Invalid file type for " . $file['name']);
    }
    
    if ($file['size'] > $max_size) {
        throw new Exception("File too large for " . $file['name']);
    }
    
    $extension = pathinfo($file['name'], PATHINFO_EXTENSION);
    $filename = $laptop_id . '_' . $prefix . '_' . time() . '.' . $extension;
    $filepath = $upload_dir . $filename;
    
    if (move_uploaded_file($file['tmp_name'], $filepath)) {
        return 'assets/images/laptops/' . $filename;
    } else {
        throw new Exception("Failed to upload " . $file['name']);
    }
}
?>