<?php
require_once('../config/db.php');

// Receive form data
$ProductID = trim($_POST['ProductID'] ?? '');
$Name = trim($_POST['Name'] ?? '');
$BuyingPrice = $_POST['BuyingPrice'] ?? 0;
$SellingPrice = $_POST['SellingPrice'] ?? 0;
$StockQuantity = $_POST['StockQuantity'] ?? 0;

// Validate required fields
if (!$ProductID || !$Name) {
    header("Location: ../products.php?error=missing_fields");
    exit;
}

// Handle photo upload
$photoName = null;

if (!empty($_FILES['Photo']['name'])) {
    $ext = pathinfo($_FILES['Photo']['name'], PATHINFO_EXTENSION);
    $photoName = "P_" . time() . "_" . rand(1000, 9999) . "." . $ext;
    move_uploaded_file($_FILES['Photo']['tmp_name'], "../uploads/" . $photoName);
}

try {
    $stmt = $pdo->prepare("
        INSERT INTO products (ProductID, Name, BuyingPrice, SellingPrice, StockQuantity, Photo)
        VALUES (?, ?, ?, ?, ?, ?)
    ");
    $stmt->execute([
        $ProductID,
        $Name,
        $BuyingPrice,
        $SellingPrice,
        $StockQuantity,
        $photoName
    ]);

} catch (PDOException $e) {
    // Duplicate ID
    if ($e->getCode() == 23000) {
        header("Location: ../products.php?error=duplicate_id");
        exit;
    }
    throw $e;
}

header("Location: ../products.php?success=added");
exit;
