<?php
session_start();
require_once '../../assets/db_connect.php';

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

if (!isset($_SESSION['user']['id'])) {
    echo json_encode(['status' => 'error', 'message' => 'Unauthorized']);
    exit();
}

try {
    // Get form data
    $product_id = $_POST['id'] ?? 0;
    $name = $_POST['name'] ?? '';
    $generic_name = $_POST['generic_name'] ?? '';
    $sku = $_POST['sku'] ?? '';
    $unit = $_POST['unit'] ?? 'tablet';
    $category = $_POST['category'] ?? '';
    $vat_percent = $_POST['vat_percent'] ?? 0;
    $buying_price = $_POST['buying_price'] ?? 0;
    $selling_price = $_POST['selling_price'] ?? 0;
    $is_active = isset($_POST['is_active']) ? 1 : 0;
    $shop_id = $_POST['shop_id'] ?? $_SESSION['user']['shop_id'];
    
    // Validate
    if (empty($name) || $buying_price <= 0 || $selling_price <= 0) {
        throw new Exception('Please fill all required fields');
    }
    
    // Check if SKU is unique (excluding current product)
    if (!empty($sku)) {
        $check_sql = "SELECT id FROM products WHERE sku = ? AND id != ? AND shop_id = ?";
        $check_stmt = $pdo->prepare($check_sql);
        $check_stmt->execute([$sku, $product_id, $shop_id]);
        if ($check_stmt->fetch()) {
            throw new Exception('SKU already exists for another product');
        }
    }
    
    // Update product
    $sql = "UPDATE products SET 
            name = ?, generic_name = ?, sku = ?, unit = ?, category = ?, 
            vat_percent = ?, buying_price = ?, selling_price = ?, is_active = ?
            WHERE id = ? AND shop_id = ?";
    
    $stmt = $pdo->prepare($sql);
    $success = $stmt->execute([
        $name, $generic_name, $sku, $unit, $category, 
        $vat_percent, $buying_price, $selling_price, $is_active,
        $product_id, $shop_id
    ]);
    
    if ($success) {
        echo json_encode([
            'status' => 'success',
            'message' => 'Product updated successfully!'
        ]);
    } else {
        throw new Exception('Failed to update product');
    }
    
} catch (Exception $e) {
    echo json_encode([
        'status' => 'error',
        'message' => $e->getMessage()
    ]);
}
?>