<?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;
    $shop_id = $_POST['shop_id'] ?? $_SESSION['user']['shop_id'];
    $name = trim($_POST['name'] ?? '');
    $generic_name = trim($_POST['generic_name'] ?? '');
    $sku = trim($_POST['sku'] ?? '');
    $unit = $_POST['unit'] ?? 'tablet';
    $category = trim($_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;
    $updated_by = $_SESSION['user']['id'];

    // Convert to proper types
    $product_id = intval($product_id);
    $vat_percent = floatval($vat_percent);
    $buying_price = floatval($buying_price);
    $selling_price = floatval($selling_price);

    // Validation
    if (empty($name)) {
        throw new Exception('Product name is required');
    }

    if ($buying_price <= 0) {
        throw new Exception('Buying price must be greater than 0');
    }

    if ($selling_price <= 0) {
        throw new Exception('Selling price must be greater than 0');
    }

    if ($selling_price < $buying_price) {
        throw new Exception('Selling price cannot be less than buying price');
    }

    // Check if product exists and belongs to shop
    $check_sql = "SELECT id FROM products WHERE id = ? AND shop_id = ?";
    $check_stmt = $pdo->prepare($check_sql);
    $check_stmt->execute([$product_id, $shop_id]);
    
    if (!$check_stmt->fetch()) {
        throw new Exception('Product not found or access denied');
    }

    // Check if SKU already exists (excluding current product)
    if (!empty($sku)) {
        $sku_check_sql = "SELECT id FROM products WHERE sku = ? AND id != ? AND shop_id = ?";
        $sku_check_stmt = $pdo->prepare($sku_check_sql);
        $sku_check_stmt->execute([$sku, $product_id, $shop_id]);
        
        if ($sku_check_stmt->fetch()) {
            throw new Exception('SKU already exists. Please use a different SKU.');
        }
    }

    // Check if product name already exists (excluding current product)
    $name_check_sql = "SELECT id FROM products WHERE name = ? AND id != ? AND shop_id = ?";
    $name_check_stmt = $pdo->prepare($name_check_sql);
    $name_check_stmt->execute([$name, $product_id, $shop_id]);
    
    if ($name_check_stmt->fetch()) {
        throw new Exception('Product name already exists. Please use a different name.');
    }

    // 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) {
        throw new Exception('Failed to update product. Please try again.');
    }

    // Check if any rows were affected
    if ($stmt->rowCount() === 0) {
        throw new Exception('No changes were made or product not found.');
    }

    echo json_encode([
        'status' => 'success',
        'message' => 'Product updated successfully!',
        'product_id' => $product_id,
        'product_name' => $name
    ]);

} catch (Exception $e) {
    http_response_code(400);
    echo json_encode([
        'status' => 'error',
        'message' => $e->getMessage()
    ]);
}