<?php
session_start();
if (!isset($_SESSION['user_id'])) { http_response_code(403); exit(json_encode(['success'=>false,'message'=>'Unauthorized'])); }
require_once '../connect.php';
$account_id = $_SESSION['account_id'];
$user_id = (int)($_SESSION['user_id'] ?? 0);
$raw    = file_get_contents('php://input');
$json   = $raw ? json_decode($raw, true) : null;
if (is_array($json)) crmDecodeIdsInArray($json);
crmDecodeIdsInArray($_POST);
$action = $_POST['action'] ?? ($json['action'] ?? '');

// Helper function to upload images
function uploadItemImages($item_id, $files, $account_id) {
    $uploadPath = getUserUploadPath() . '/';
    if (!is_dir($uploadPath)) {
        mkdir($uploadPath, 0755, true);
    }
    
    $uploaded = [];
    $isFirst = true;
    
    foreach ($files['tmp_name'] as $index => $tmp_name) {
        if ($files['error'][$index] === UPLOAD_ERR_OK) {
            $ext = pathinfo($files['name'][$index], PATHINFO_EXTENSION);
            $filename = 'item_' . $item_id . '_' . time() . '_' . $index . '.' . $ext;
            $filepath = $uploadPath . $filename;
            // $dbpath =     $filename;
            
            if (move_uploaded_file($tmp_name, $filepath)) {
                $is_primary = $isFirst ? 1 : 0;
                $GLOBALS['conn']->query("INSERT INTO item_images (item_id, image_path, is_primary, sort_order) VALUES ($item_id, '$filename', $is_primary, $index)");
                $uploaded[] = $filename;
                $isFirst = false;
            }
        }
    }
    return $uploaded;
}

switch ($action) {
    case 'add':
    case 'edit':
        requirePermission($conn, 'items', ($_POST['edit_id'] ?? 0) ? 'edit' : 'add');
        $name    = sanitize($conn, $_POST['name'] ?? '');
        $desc    = sanitize($conn, $_POST['description'] ?? '');
        $price   = (float)($_POST['price'] ?? 0);
        $currency = sanitize($conn, $_POST['currency'] ?? '');
        if (!$currency) { $cq=$conn->query("SELECT currency FROM accounts WHERE id=$account_id LIMIT 1"); $currency=($cq&&$cq->num_rows)?($cq->fetch_assoc()['currency']?:'USD'):'USD'; }
        $forceDuplicate = (int)($_POST['force_duplicate'] ?? 0);
        $type_id = (int)($_POST['items_type_id'] ?? 0);
        $category_id = $_POST['category_id'] && $_POST['category_id'] !== '' ? (int)$_POST['category_id'] : 'NULL';
        $edit_id = (int)($_POST['edit_id'] ?? 0);
        
        if (!$name) jsonResponse(false, 'Item name required');
        if (!$type_id) jsonResponse(false, 'Item type required');
        $dup = $conn->query("SELECT id FROM items WHERE account_id=$account_id AND LOWER(name)=LOWER('$name')" . ($edit_id ? " AND id<>$edit_id" : "") . " LIMIT 1");
        if ($dup && $dup->num_rows && !$forceDuplicate) jsonResponse(false, 'DUPLICATE_ITEM_NAME: An item with this name already exists. Submit again if you still want to save it.');
        
        if ($edit_id) {
            $conn->query("UPDATE items SET 
                name='$name', 
                description='$desc', 
                price=$price, 
                currency='$currency',
                items_type_id=$type_id, 
                category_id=" . ($category_id === 'NULL' ? 'NULL' : $category_id) . " 
                WHERE id=$edit_id AND account_id=$account_id");
            $item_id = $edit_id;
        } else {
            if (columnExists($conn,'items','added_by')) {
                $conn->query("INSERT INTO items (name, description, price, currency, items_type_id, category_id, account_id, added_by) 
                    VALUES ('$name','$desc',$price,'$currency',$type_id," . ($category_id === 'NULL' ? 'NULL' : $category_id) . ",$account_id,$user_id)");
            } else {
                $conn->query("INSERT INTO items (name, description, price, currency, items_type_id, category_id, account_id) 
                    VALUES ('$name','$desc',$price,'$currency',$type_id," . ($category_id === 'NULL' ? 'NULL' : $category_id) . ",$account_id)");
            }
            $item_id = $conn->insert_id;
        }
        
        // Handle image uploads
        if (isset($_FILES['images']) && !empty($_FILES['images']['name'][0])) {
            uploadItemImages($item_id, $_FILES['images'], $account_id);
        }
        
        jsonResponse(true, $edit_id ? 'Item updated' : 'Item added', ['id' => crmEncodeId($item_id)]);
        
    case 'get':
        $id = (int)($json['id'] ?? $_POST['id'] ?? 0);
        $r  = $conn->query("SELECT * FROM items WHERE id=$id AND account_id=$account_id")->fetch_assoc();
        if (!$r) jsonResponse(false, 'Not found');
        
        // Get images
        $images = [];
        $img_res = $conn->query("SELECT * FROM item_images WHERE item_id=$id ORDER BY is_primary DESC, sort_order ASC");
        while ($img = $img_res->fetch_assoc()) {
            $images[] = $img;
        }
        
        jsonResponse(true, '', ['data' => $r, 'images' => $images]);
        
    case 'delete':
        requirePermission($conn, 'items', 'delete');
        $id = (int)($json['id'] ?? $_POST['id'] ?? 0);
        
        // Check if item is used in any lead
        $chk = $conn->query("SELECT id FROM leads WHERE item_id=$id AND account_id=$account_id LIMIT 1");
        if ($chk->num_rows > 0) {
            jsonResponse(false, 'Cannot delete item: it is used in one or more leads');
        }
        
        // Delete images from filesystem
        $img_res = $conn->query("SELECT image_path FROM item_images WHERE item_id=$id");
        while ($img = $img_res->fetch_assoc()) {
            $filepath = str_replace(UPLOAD_URL, UPLOAD_DIR, $img['image_path']);
            if (file_exists($filepath)) unlink($filepath);
        }
        
        $conn->query("DELETE FROM items WHERE id=$id AND account_id=$account_id");
        jsonResponse(true, 'Item deleted');
        
    case 'remove_image':
        requirePermission($conn, 'items', 'edit');
        $image_id = (int)($json['image_id'] ?? $_POST['image_id'] ?? 0);
        $img = $conn->query("SELECT i.* FROM item_images i 
            JOIN items it ON it.id = i.item_id 
            WHERE i.id=$image_id AND it.account_id=$account_id")->fetch_assoc();
        if ($img) {
            $filepath = str_replace(UPLOAD_URL, UPLOAD_DIR, $img['image_path']);
            if (file_exists($filepath)) unlink($filepath);
            $conn->query("DELETE FROM item_images WHERE id=$image_id");
            jsonResponse(true, 'Image removed');
        } else {
            jsonResponse(false, 'Image not found');
        }
        
    case 'set_primary':
        requirePermission($conn, 'items', 'edit');
        $image_id = (int)($json['image_id'] ?? $_POST['image_id'] ?? 0);
        // Get item_id from the image
        $img = $conn->query("SELECT item_id FROM item_images WHERE id=$image_id")->fetch_assoc();
        if ($img) {
            $conn->query("UPDATE item_images SET is_primary=0 WHERE item_id={$img['item_id']}");
            $conn->query("UPDATE item_images SET is_primary=1 WHERE id=$image_id");
            jsonResponse(true, 'Primary image set');
        } else {
            jsonResponse(false, 'Image not found');
        }
        
    default:
        jsonResponse(false, 'Invalid action');
}