<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $products = json_decode(file_get_contents('../js/products.json'), true);
    
    if ($_POST['action'] === 'create') {
        $newProduct = [
            'id' => uniqid(),
            'name' => $_POST['name'],
            'selling_price' => $_POST['selling_price'],
            'mrp' => $_POST['mrp'],
            'img1' => $_POST['img1'],
            'img2' => $_POST['img2'],
            'img3' => $_POST['img3'],
            'img4' => $_POST['img4'],
            'img5' => $_POST['img5'],
            'color' => 'Default',
            'size' => 'Free Size',
            'storage' => '',
            'fetaures' => '',
            'verients' => [],
            'disp_order' => 0,
            'from_csv' => "0",
            'created_at' => date('Y-m-d H:i:s'),
            'md5_id' => md5($_POST['name'] . uniqid())
        ];
        array_push($products, $newProduct);
    } 
    elseif ($_POST['action'] === 'update') {
        foreach ($products as &$product) {
            if ($product['id'] === $_POST['id']) {
                $product['name'] = $_POST['name'];
                $product['selling_price'] = $_POST['selling_price'];
                $product['mrp'] = $_POST['mrp'];
                $product['img1'] = $_POST['img1'];
                $product['img2'] = $_POST['img2'];
                $product['img3'] = $_POST['img3'];
                $product['img4'] = $_POST['img4'];
                $product['img5'] = $_POST['img5'];
                foreach ($product['verients'] as &$variant) {
                    $variant['name'] = $_POST['name'];
                    $variant['selling_price'] = $_POST['selling_price'];
                    $variant['mrp'] = $_POST['mrp'];
                }
                break;
            }
        }
    }
    
    file_put_contents('../js/products.json', json_encode($products, JSON_PRETTY_PRINT));
    header('Location: main.php');
    exit;
}