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

$ProductID      = $_POST['ProductID'] ?? '';
$Name           = trim($_POST['Name'] ?? '');
$BuyingPrice    = floatval($_POST['BuyingPrice'] ?? 0);
$SellingPrice   = floatval($_POST['SellingPrice'] ?? 0);
$StockQuantity  = intval($_POST['StockQuantity'] ?? 0);

if (!$ProductID) {
    header("Location: ../public/products.php?error=no_id");
    exit;
}

// Get old product info
$stmt = $pdo->prepare("SELECT Photo FROM products WHERE ProductID = ?");
$stmt->execute([$ProductID]);
$existing = $stmt->fetch();

$oldPhoto = $existing['Photo'] ?? null;
$newPhoto = $oldPhoto;

// Handle photo upload
if (!empty($_FILES['Photo']['name'])) {

    $ext = strtolower(pathinfo($_FILES['Photo']['name'], PATHINFO_EXTENSION));
    $newPhoto = "P_" . time() . "_" . rand(1000, 9999) . "." . $ext;

    move_uploaded_file($_FILES['Photo']['tmp_name'], "../uploads/" . $newPhoto);

    // Delete old photo if exists
    if ($oldPhoto && file_exists("../uploads/" . $oldPhoto)) {
        unlink("../uploads/" . $oldPhoto);
    }
}

// Update product
$stmt = $pdo->prepare("
    UPDATE products
    SET Name=?, BuyingPrice=?, SellingPrice=?, StockQuantity=?, Photo=?
    WHERE ProductID=?
");

$stmt->execute([
    $Name,
    $BuyingPrice,
    $SellingPrice,
    $StockQuantity,
    $newPhoto,
    $ProductID
]);

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