<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

require_once '../../config/cors.php';
require_once '../../config/database.php';

$database = new Database();
$db = $database->getConnection();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        $db->beginTransaction();

        // Check if we already have data
        $orderCheck = $db->prepare("SELECT COUNT(*) as count FROM orders");
        $orderCheck->execute();
        $orderCount = $orderCheck->fetch(PDO::FETCH_ASSOC)['count'];

        if ($orderCount > 0) {
            echo json_encode([
                'success' => false,
                'message' => 'Data already exists. Seeding skipped.',
                'existing_orders' => (int)$orderCount
            ]);
            return;
        }

        // Insert sample categories if they don't exist
        $categoryCheck = $db->prepare("SELECT COUNT(*) as count FROM categories");
        $categoryCheck->execute();
        $categoryCount = $categoryCheck->fetch(PDO::FETCH_ASSOC)['count'];

        if ($categoryCount == 0) {
            $categories = [
                ['Mobiles', 'Mobile phones and smartphones'],
                ['Accessories', 'Mobile accessories and gadgets'],
                ['Cases', 'Phone cases and covers'],
                ['Chargers', 'Chargers and power banks']
            ];

            foreach ($categories as $cat) {
                $stmt = $db->prepare("INSERT INTO categories (name, description, created_at) VALUES (?, ?, NOW())");
                $stmt->execute([$cat[0], $cat[1]]);
            }
        }

        // Insert sample users if they don't exist
        $userCheck = $db->prepare("SELECT COUNT(*) as count FROM users");
        $userCheck->execute();
        $userCount = $userCheck->fetch(PDO::FETCH_ASSOC)['count'];

        if ($userCount == 0) {
            $users = [
                ['John Doe', 'john@example.com', password_hash('password123', PASSWORD_DEFAULT), '9876543210'],
                ['Jane Smith', 'jane@example.com', password_hash('password123', PASSWORD_DEFAULT), '9876543211'],
                ['Mike Johnson', 'mike@example.com', password_hash('password123', PASSWORD_DEFAULT), '9876543212'],
                ['Sarah Wilson', 'sarah@example.com', password_hash('password123', PASSWORD_DEFAULT), '9876543213'],
                ['David Brown', 'david@example.com', password_hash('password123', PASSWORD_DEFAULT), '9876543214']
            ];

            foreach ($users as $user) {
                $stmt = $db->prepare("INSERT INTO users (name, email, password, phone, created_at) VALUES (?, ?, ?, ?, NOW())");
                $stmt->execute($user);
            }
        }

        // Get category and user IDs
        $categoryStmt = $db->prepare("SELECT id, name FROM categories");
        $categoryStmt->execute();
        $categories = $categoryStmt->fetchAll(PDO::FETCH_ASSOC);

        $userStmt = $db->prepare("SELECT id FROM users LIMIT 5");
        $userStmt->execute();
        $users = $userStmt->fetchAll(PDO::FETCH_ASSOC);

        // Insert sample products if they don't exist
        $productCheck = $db->prepare("SELECT COUNT(*) as count FROM products");
        $productCheck->execute();
        $productCount = $productCheck->fetch(PDO::FETCH_ASSOC)['count'];

        if ($productCount == 0 && !empty($categories)) {
            $products = [
                ['iPhone 14 Pro', 'Latest iPhone with advanced features', 89999, $categories[0]['id'], 'iphone14pro.jpg'],
                ['Samsung Galaxy S23', 'Premium Android smartphone', 79999, $categories[0]['id'], 'galaxys23.jpg'],
                ['Wireless Earbuds', 'High-quality wireless earbuds', 4999, $categories[1]['id'], 'earbuds.jpg'],
                ['Phone Case Premium', 'Protective phone case', 1299, $categories[2]['id'], 'case.jpg'],
                ['Fast Charger 65W', 'Quick charging adapter', 2499, $categories[3]['id'], 'charger.jpg'],
                ['OnePlus 11', 'Flagship OnePlus smartphone', 69999, $categories[0]['id'], 'oneplus11.jpg'],
                ['Power Bank 20000mAh', 'High capacity power bank', 3999, $categories[3]['id'], 'powerbank.jpg'],
                ['Bluetooth Speaker', 'Portable wireless speaker', 5999, $categories[1]['id'], 'speaker.jpg']
            ];

            foreach ($products as $product) {
                $stmt = $db->prepare("INSERT INTO products (name, description, price, category_id, image, stock, created_at) VALUES (?, ?, ?, ?, ?, 50, NOW())");
                $stmt->execute($product);
            }
        }

        // Get product IDs
        $productStmt = $db->prepare("SELECT id, price FROM products");
        $productStmt->execute();
        $products = $productStmt->fetchAll(PDO::FETCH_ASSOC);

        // Insert sample orders with realistic dates
        if (!empty($users) && !empty($products)) {
            $statuses = ['pending', 'processing', 'delivered', 'cancelled'];
            $orderCount = 0;

            // Create orders for the last 30 days
            for ($i = 30; $i >= 0; $i--) {
                $ordersPerDay = rand(1, 5);
                
                for ($j = 0; $j < $ordersPerDay; $j++) {
                    $user = $users[array_rand($users)];
                    $status = $statuses[array_rand($statuses)];
                    $orderDate = date('Y-m-d H:i:s', strtotime("-$i days") + rand(0, 86400));
                    
                    // Calculate total price
                    $numItems = rand(1, 3);
                    $totalPrice = 0;
                    $orderItems = [];
                    
                    for ($k = 0; $k < $numItems; $k++) {
                        $product = $products[array_rand($products)];
                        $quantity = rand(1, 2);
                        $price = $product['price'];
                        $totalPrice += $price * $quantity;
                        $orderItems[] = [
                            'product_id' => $product['id'],
                            'quantity' => $quantity,
                            'price' => $price
                        ];
                    }

                    // Insert order
                    $orderStmt = $db->prepare("INSERT INTO orders (user_id, total_price, status, created_at) VALUES (?, ?, ?, ?)");
                    $orderStmt->execute([$user['id'], $totalPrice, $status, $orderDate]);
                    $orderId = $db->lastInsertId();

                    // Insert order items
                    foreach ($orderItems as $item) {
                        $itemStmt = $db->prepare("INSERT INTO order_items (order_id, product_id, quantity, price, created_at) VALUES (?, ?, ?, ?, ?)");
                        $itemStmt->execute([$orderId, $item['product_id'], $item['quantity'], $item['price'], $orderDate]);
                    }

                    $orderCount++;
                }
            }
        }

        $db->commit();

        echo json_encode([
            'success' => true,
            'message' => 'Sample data seeded successfully',
            'data' => [
                'categories' => count($categories),
                'users' => count($users),
                'products' => count($products),
                'orders' => $orderCount ?? 0
            ]
        ]);

    } catch (PDOException $e) {
        $db->rollBack();
        http_response_code(500);
        echo json_encode([
            'success' => false,
            'error' => 'Seeding failed: ' . $e->getMessage()
        ]);
    }
} else {
    http_response_code(405);
    echo json_encode([
        'success' => false,
        'error' => 'Method not allowed'
    ]);
}
?>