<?php  
include 'config.php';  

header('Content-Type: application/json');

$title = $_POST['title'] ?? '';  
$amount = $_POST['amount'] ?? 0;  
$discount = $_POST['discount'] ?? 0;  
$description = $_POST['description'] ?? '';  
$stock = $_POST['stock'] ?? 0;  

// NEW PARAM
$sold = $_POST['sold'] ?? 0;

// MAIN IMAGE
$image_link = $_POST['image_link'] ?? '';

// GALLERY IMAGES
$images = json_decode($_POST['images'] ?? '[]', true);  

if(empty($title)){  
    die(json_encode([  
        "status" => "failed",  
        "message" => "Title required"  
    ]));  
}  

/*
|--------------------------------------------------------------------------
| INSERT PRODUCT
|--------------------------------------------------------------------------
*/

$stmt = $conn->prepare("  
INSERT INTO products  
(title, amount, discount, description, stock, sold, image_link)  
VALUES  
(?,?,?,?,?,?,?)  
");  

$stmt->bind_param(  
    "sddsiis",  
    $title,  
    $amount,  
    $discount,  
    $description,  
    $stock,  
    $sold,  
    $image_link  
);  

if($stmt->execute()){  

    $product_id = $conn->insert_id;  

    /*
    |--------------------------------------------------------------------------
    | INSERT GALLERY IMAGES
    |--------------------------------------------------------------------------
    */

    if(is_array($images)){

        foreach($images as $img){  

            $img = trim($img);  

            if(!empty($img)){

                $imgStmt = $conn->prepare("  
                INSERT INTO product_images  
                (product_id, image_link)  
                VALUES (?,?)  
                ");  

                $imgStmt->bind_param(  
                    "is",  
                    $product_id,  
                    $img  
                );  

                $imgStmt->execute();  
            }
        }
    }

    // LEFT CALCULATION
    $left = $stock - $sold;

    echo json_encode([  
        "status" => "success",  
        "message" => "Product Added Successfully",  
        "product_id" => $product_id,
        "sold" => $sold,
        "left" => $left
    ]);  

}else{  

    echo json_encode([  
        "status" => "failed",  
        "message" => "Insert Failed"  
    ]);  
}  
?>