<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $products = json_decode(file_get_contents('../js/products.json'), true);
    
    // Build variants array from form data
    function buildVariants($post) {
        $verients = [];

        // COLOR VARIANTS
        $colorNames = $post['color_name'] ?? [];
        $colorImgs  = $post['color_img']  ?? [];
        $colorSelectedVals = $post['color_selected'] ?? [];

        $colorOptions = [];
        foreach ($colorNames as $idx => $name) {
            $name = trim($name);
            if ($name === '') continue;
            $img = isset($colorImgs[$idx]) ? trim($colorImgs[$idx]) : '';
            // selected checkbox value is 1-based count
            $isSelected = in_array((string)($idx + 1), (array)$colorSelectedVals);
            $opt = ['name' => $name, 'selected' => $isSelected];
            if ($img !== '') $opt['img'] = $img;
            $colorOptions[] = $opt;
        }
        if (!empty($colorOptions)) {
            $verients[] = [
                'type'    => 'color',
                'label'   => 'Color',
                'options' => $colorOptions
            ];
        }

        // STORAGE VARIANTS
        $storageOptions = $post['storage_option'] ?? [];
        $storageSelectedVals = $post['storage_selected'] ?? [];
        $storageLabel = $post['storage_label'] ?? 'Storage';

        $storageType = 'storage';
        if ($storageLabel === 'RAM + Storage') $storageType = 'ram_storage';
        elseif ($storageLabel === 'Model') $storageType = 'model';

        $stOpts = [];
        foreach ($storageOptions as $idx => $name) {
            $name = trim($name);
            if ($name === '') continue;
            $isSelected = in_array((string)($idx + 1), (array)$storageSelectedVals);
            $stOpts[] = ['name' => $name, 'selected' => $isSelected];
        }
        if (!empty($stOpts)) {
            $verients[] = [
                'type'    => $storageType,
                'label'   => $storageLabel,
                'options' => $stOpts
            ];
        }

        return $verients;
    }

    if ($_POST['action'] === 'create') {
        $newProduct = [
            'id'           => uniqid(),
            'name'         => trim($_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'     => trim($_POST['features'] ?? ''),
            'verients'     => buildVariants($_POST),
            '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']          = trim($_POST['name']);
                $product['selling_price'] = $_POST['selling_price'];
                $product['mrp']           = $_POST['mrp'];
                $product['img1']          = $_POST['img1'] ?? $product['img1'];
                $product['img2']          = $_POST['img2'] ?? $product['img2'];
                $product['img3']          = $_POST['img3'] ?? $product['img3'];
                $product['img4']          = $_POST['img4'] ?? $product['img4'];
                $product['img5']          = $_POST['img5'] ?? $product['img5'];
                $product['fetaures']      = trim($_POST['features'] ?? $product['fetaures']);
                $product['verients']      = buildVariants($_POST);
                break;
            }
        }
        unset($product);
    }

    file_put_contents('../js/products.json', json_encode($products, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
    header('Location: main.php');
    exit;
}
