<?php
require_once '../includes/auth.php';
require_once '../includes/db.php';
require_once '../includes/functions.php';

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

if (!isLoggedIn()) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

// Support both JSON and FormData
$json = json_decode(file_get_contents('php://input'), true);
$action = $_POST['action'] ?? $json['action'] ?? '';

switch ($action) {
    case 'save':
        $id = $_POST['id'] ?? $json['product']['id'] ?? '';
        $name = $_POST['name'] ?? $json['product']['name'] ?? '';
        $sku = $_POST['sku'] ?? $json['product']['sku'] ?? '';
        $description = $_POST['description'] ?? $json['product']['description'] ?? '';
        $materials = isset($_POST['materials']) ? json_decode($_POST['materials'], true) : ($json['product']['materials'] ?? []);
        $company_id = $_SESSION['company_id'];
        
        // SKU validation: PRD-XXXXXXXX (8 digits)
        if (!preg_match('/^PRD-\d{8}$/', $sku)) {
            echo json_encode(['success' => false, 'message' => 'Invalid SKU format. Must be PRD-XXXXXXXX']);
            exit;
        }

        // Uniqueness check
        $existing = fetch("SELECT id FROM products WHERE sku = ? AND id != ?", [$sku, $id]);
        if ($existing) {
            echo json_encode(['success' => false, 'message' => 'This SKU is already in use']);
            exit;
        }
        
        try {
            $pdo->beginTransaction();

            $base_price = $_POST['base_price'] ?? $json['product']['base_price'] ?? 0.00;
            if ($id) {
                $sql = "UPDATE products SET sku=?, name=?, buyer_id=?, base_price=?, description=? WHERE id=? AND company_id=?";
                query($sql, [$sku, $name, $_POST['buyer_id'] ?? $json['product']['buyer_id'], $base_price, $description, $id, $company_id]);
                $productId = $id;
                logAudit('PRODUCT_UPDATE', "Updated style: $name (SKU: $sku)");
            } else {
                $sql = "INSERT INTO products (company_id, sku, name, buyer_id, base_price, description) VALUES (?, ?, ?, ?, ?, ?)";
                query($sql, [$company_id, $sku, $name, $_POST['buyer_id'] ?? $json['product']['buyer_id'], $base_price, $description]);
                $productId = $pdo->lastInsertId();
                logAudit('PRODUCT_CREATE', "Created style: $name (SKU: $sku)");
            }

            // Save BOM materials
            query("DELETE FROM inventory_item_product WHERE product_id = ?", [$productId]);
            if (!empty($materials)) {
                foreach ($materials as $material) {
                    $sql = "INSERT INTO inventory_item_product (product_id, inventory_item_id, quantity, wastage_quantity, wastage_reason) VALUES (?, ?, ?, ?, ?)";
                    query($sql, [
                        $productId, 
                        $material['inventory_item_id'], 
                        $material['quantity'], 
                        $material['wastage_quantity'] ?: 0, 
                        $material['wastage_reason'] ?: ''
                    ]);
                }
            }

            // Handle Sample Uploads
            if (!empty($_FILES['samples'])) {
                $uploadDir = '../uploads/products/';
                if (!is_dir($uploadDir)) mkdir($uploadDir, 0777, true);

                foreach ($_FILES['samples']['tmp_name'] as $key => $tmpName) {
                    if ($_FILES['samples']['error'][$key] === UPLOAD_ERR_OK) {
                        $fileName = $_FILES['samples']['name'][$key];
                        $fileExt = pathinfo($fileName, PATHINFO_EXTENSION);
                        $uniqueName = uniqid('sample_') . '.' . $fileExt;
                        $filePath = 'uploads/products/' . $uniqueName;

                        if (move_uploaded_file($tmpName, $uploadDir . $uniqueName)) {
                            query("INSERT INTO product_samples (product_id, file_path, file_name, file_type) VALUES (?, ?, ?, ?)", [
                                $productId,
                                $filePath,
                                $fileName,
                                $_FILES['samples']['type'][$key]
                            ]);
                        }
                    }
                }
            }

            $pdo->commit();
            echo json_encode(['success' => true, 'message' => $id ? 'Product updated successfully' : 'New product added']);
        } catch (Exception $e) {
            if ($pdo->inTransaction()) $pdo->rollBack();
            echo json_encode(['success' => false, 'message' => 'Error saving product: ' . $e->getMessage()]);
        }
        break;

    case 'remove_sample':
        $sampleId = $_POST['sample_id'] ?? $json['sample_id'] ?? '';
        try {
            $sample = fetch("SELECT * FROM product_samples WHERE id = ?", [$sampleId]);
            if ($sample) {
                if (file_exists('../' . $sample['file_path'])) {
                    unlink('../' . $sample['file_path']);
                }
                query("DELETE FROM product_samples WHERE id = ?", [$sampleId]);
                echo json_encode(['success' => true, 'message' => 'Sample removed']);
            } else {
                echo json_encode(['success' => false, 'message' => 'Sample not found']);
            }
        } catch (Exception $e) {
            echo json_encode(['success' => false, 'message' => 'Error: ' . $e->getMessage()]);
        }
        break;

    case 'get':
        $id = $_GET['id'] ?? $json['id'] ?? '';
        try {
            $product = fetch("SELECT p.*, b.name as buyer_name FROM products p LEFT JOIN buyers b ON p.buyer_id = b.id WHERE p.id = ?", [$id]);
            if ($product) {
                $product['materials'] = fetchAll("SELECT es.*, i.name, i.unit, i.sku FROM inventory_item_product es JOIN inventory_items i ON es.inventory_item_id = i.id WHERE es.product_id = ?", [$id]);
                $product['samples'] = fetchAll("SELECT * FROM product_samples WHERE product_id = ?", [$id]);
                echo json_encode(['success' => true, 'product' => $product]);
            } else {
                echo json_encode(['success' => false, 'message' => 'Product not found']);
            }
        } catch (Exception $e) {
            echo json_encode(['success' => false, 'message' => 'Error: ' . $e->getMessage()]);
        }
        break;

    case 'delete':
        $id = $_POST['id'] ?? $json['id'] ?? '';
        $company_id = $_SESSION['company_id'];
        
        // Check if product is used in any production lines
        $inLine = fetch("SELECT id FROM production_line_products WHERE product_id = ?", [$id]);
        if ($inLine) {
            echo json_encode(['success' => false, 'message' => 'Cannot delete product as it is currently assigned to one or more production lines.']);
            exit;
        }

        try {
            $pdo->beginTransaction();
            
            $p = fetch("SELECT name, sku FROM products WHERE id = ? AND company_id = ?", [$id, $company_id]);
            if (!$p) {
                echo json_encode(['success' => false, 'message' => 'Product not found']);
                exit;
            }

            // 1. Delete BOM entries
            query("DELETE FROM inventory_item_product WHERE product_id = ?", [$id]);
            
            // 2. Delete product
            query("DELETE FROM products WHERE id = ? AND company_id = ?", [$id, $company_id]);
            
            logAudit('PRODUCT_DELETE', "Deleted style: {$p['name']} (SKU: {$p['sku']})");
            
            $pdo->commit();
            echo json_encode(['success' => true, 'message' => 'Product deleted successfully']);
        } catch (Exception $e) {
            if ($pdo->inTransaction()) $pdo->rollBack();
            echo json_encode(['success' => false, 'message' => 'Error deleting product: ' . $e->getMessage()]);
        }
        break;

    default:
        echo json_encode(['success' => false, 'message' => 'Invalid action']);
        break;
}
