<?php
if (session_status() === PHP_SESSION_NONE) session_start();
if (!isset($_SESSION['user_id']) || ($_SESSION['user_role_name'] ?? '') !== 'Administrator') {
    // If not admin, we might want to redirect or show error in view.
    // For now, we'll let the view handle the error display or we can set a flag.
    $access_denied = true;
    return;
}

$db = db();
$outlets = $db->query("SELECT * FROM outlets ORDER BY id")->fetchAll();
$message = "";

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $source_id = (int)$_POST['source_id'];
    $target_id = (int)$_POST['target_id'];
    $copy_items = isset($_POST['copy_items']);
    $copy_categories = isset($_POST['copy_categories']);
    $copy_units = isset($_POST['copy_units']);
    $copy_suppliers = isset($_POST['copy_suppliers']);
    
    if ($source_id === $target_id) {
        $message = "<div class='alert alert-danger'>Source and Target cannot be the same.</div>";
    } else {
        try {
            $db->beginTransaction();
            
            // Helpers
            function get_target_id($db, $table, $col_name, $val, $target_oid) {
                $stmt = $db->prepare("SELECT id FROM $table WHERE $col_name = ? AND outlet_id = ?");
                $stmt->execute([$val, $target_oid]);
                return $stmt->fetchColumn();
            }
            
            // 1. Categories
            $cat_map = []; // source_id => target_id
            if ($copy_categories || $copy_items) {
                $cats = $db->prepare("SELECT * FROM stock_categories WHERE outlet_id = ?");
                $cats->execute([$source_id]);
                while ($c = $cats->fetch()) {
                    $tid = get_target_id($db, 'stock_categories', 'name_en', $c['name_en'], $target_id);
                    if ($tid) {
                        // Update existing category
                        $upd = $db->prepare("UPDATE stock_categories SET name_ar = ? WHERE id = ?");
                        $upd->execute([$c['name_ar'], $tid]);
                    } else {
                        // Insert new category
                        $ins = $db->prepare("INSERT INTO stock_categories (name_en, name_ar, outlet_id) VALUES (?, ?, ?)");
                        $ins->execute([$c['name_en'], $c['name_ar'], $target_id]);
                        $tid = $db->lastInsertId();
                    }
                    $cat_map[$c['id']] = $tid;
                }
            }
            
            // 2. Units
            $unit_map = [];
            if ($copy_units || $copy_items) {
                $units = $db->prepare("SELECT * FROM stock_units WHERE outlet_id = ?");
                $units->execute([$source_id]);
                while ($u = $units->fetch()) {
                    $tid = get_target_id($db, 'stock_units', 'name_en', $u['name_en'], $target_id);
                    if ($tid) {
                        // Update existing unit
                        $upd = $db->prepare("UPDATE stock_units SET name_ar = ?, short_name_en = ?, short_name_ar = ? WHERE id = ?");
                        $upd->execute([$u['name_ar'], $u['short_name_en'], $u['short_name_ar'], $tid]);
                    } else {
                        // Insert new unit
                        $ins = $db->prepare("INSERT INTO stock_units (name_en, name_ar, short_name_en, short_name_ar, outlet_id) VALUES (?, ?, ?, ?, ?)");
                        $ins->execute([$u['name_en'], $u['name_ar'], $u['short_name_en'], $u['short_name_ar'], $target_id]);
                        $tid = $db->lastInsertId();
                    }
                    $unit_map[$u['id']] = $tid;
                }
            }
            
            // 3. Suppliers
            $sup_map = [];
            if ($copy_suppliers || $copy_items) {
                $sups = $db->prepare("SELECT * FROM suppliers WHERE outlet_id = ?");
                $sups->execute([$source_id]);
                while ($s = $sups->fetch()) {
                    $tid = get_target_id($db, 'suppliers', 'name', $s['name'], $target_id);
                    if ($tid) {
                        // Update existing supplier
                        $upd = $db->prepare("UPDATE suppliers SET email = ?, phone = ?, tax_id = ?, credit_limit = ? WHERE id = ?");
                        $upd->execute([$s['email'], $s['phone'], $s['tax_id'], $s['credit_limit'], $tid]);
                    } else {
                        // Insert new supplier
                        $ins = $db->prepare("INSERT INTO suppliers (name, email, phone, tax_id, balance, credit_limit, created_at, outlet_id) VALUES (?, ?, ?, ?, 0, ?, NOW(), ?)");
                        $ins->execute([$s['name'], $s['email'], $s['phone'], $s['tax_id'], $s['credit_limit'], $target_id]);
                        $tid = $db->lastInsertId();
                    }
                    $sup_map[$s['id']] = $tid;
                }
            }
            
            // 4. Items
            if ($copy_items) {
                $items = $db->prepare("SELECT * FROM stock_items WHERE outlet_id = ?");
                $items->execute([$source_id]);
                while ($i = $items->fetch()) {
                    // Check existence by SKU
                    $check = $db->prepare("SELECT id FROM stock_items WHERE sku = ? AND outlet_id = ?");
                    $check->execute([$i['sku'], $target_id]);
                    $exists_id = $check->fetchColumn();
                    
                    $new_cat = $cat_map[$i['category_id']] ?? null;
                    $new_unit = $unit_map[$i['unit_id']] ?? null;
                    $new_sup = $sup_map[$i['supplier_id']] ?? null;
                    
                    if ($exists_id) {
                        // Update Definition (Price, Names, etc) BUT KEEP STOCK QUANTITY
                        $upd = $db->prepare("UPDATE stock_items SET name_en=?, name_ar=?, category_id=?, unit_id=?, supplier_id=?, sale_price=?, purchase_price=?, min_stock_level=?, vat_rate=?, image_path=?, is_promotion=?, promotion_start=?, promotion_end=?, promotion_percent=? WHERE id=?");
                        $upd->execute([
                            $i['name_en'], $i['name_ar'], $new_cat, $new_unit, $new_sup, 
                            $i['sale_price'], $i['purchase_price'], $i['min_stock_level'], $i['vat_rate'], $i['image_path'],
                            $i['is_promotion'], $i['promotion_start'], $i['promotion_end'], $i['promotion_percent'],
                            $exists_id
                        ]);
                    } else {
                        // Insert New
                        // Start with 0 stock unless requested (User said "remains stock quantity as it" for existing. For new, we assume 0 or copy? 0 is safer for "Copy Data" vs "Transfer Stock").
                        $ins = $db->prepare("INSERT INTO stock_items (name_en, name_ar, category_id, unit_id, supplier_id, sku, sale_price, purchase_price, stock_quantity, min_stock_level, image_path, vat_rate, expiry_date, is_promotion, promotion_start, promotion_end, promotion_percent, outlet_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
                        $ins->execute([
                            $i['name_en'], $i['name_ar'], $new_cat, $new_unit, $new_sup, $i['sku'],
                            $i['sale_price'], $i['purchase_price'], 0, $i['min_stock_level'], $i['image_path'],
                            $i['vat_rate'], $i['expiry_date'], $i['is_promotion'], $i['promotion_start'], $i['promotion_end'], $i['promotion_percent'],
                            $target_id
                        ]);
                    }
                }
            }
            
            $db->commit();
            $message = "<div class='alert alert-success'>Data copied and synced successfully!</div>";
        } catch (Exception $e) {
            $db->rollBack();
            $message = "<div class='alert alert-danger'>Error: " . $e->getMessage() . "</div>";
        }
    }
}
