<?php

/**
 * Agentic Square - Premium Admin Control Console: Asset Configuration Update Engine
 * Path: admin/edit-item.php
 */

// Inject Core Global Application Engine Paths
require_once __DIR__ . '/../config/config.php';

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

/**
 * STRICT SECURITY AUDIT GUARD (Envato Marketplace Compliant)
 * Intercepts unauthorized sessions, non-admins, and direct URL entry bypass attempts.
 */
if (!isset($_SESSION['user_id']) || !isset($_SESSION['user_role']) || $_SESSION['user_role'] !== 'admin') {
    header('Location: ../login.php');
    exit;
}

$error_msg = '';
$success_msg = '';

// Capture structural identity target parameter
$item_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

if ($item_id <= 0) {
    header('Location: admin-dashboard.php');
    exit;
}

// 1. Hydrate foundational record entity array directly matching target key nodes
$stmt = $pdo->prepare("
    SELECT i.*, s.seller_name 
    FROM items i 
    LEFT JOIN sellers s ON i.seller_id = s.id 
    WHERE i.id = ? 
    LIMIT 1
");
$stmt->execute([$item_id]);
$item = $stmt->fetch();

if (!$item) {
    header('Location: admin-dashboard.php?error=item_not_found');
    exit;
}

// 2. Extract Category configurations for dropdown layout normalization mapping loops
$categories = $pdo->query("SELECT * FROM categories ORDER BY category_name ASC")->fetchAll();

/**
 * DATABASE MUTATION TRANSACTION PIPELINE
 * Processes form submissions, structures file storage paths, and patches target record values.
 */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Collect text input variables securely
    $item_name      = trim($_POST['item_name'] ?? '');
    $item_slug      = trim($_POST['item_slug'] ?? '');
    $category_id    = (int)($_POST['category_id'] ?? 0);
    $amount         = (float)($_POST['amount'] ?? 0.00);
    $item_details   = trim($_POST['item_details'] ?? '');
    $video_url      = trim($_POST['video_url'] ?? '');
    $demo_url       = trim($_POST['demo_url'] ?? '');
    $files_included = trim($_POST['files_included'] ?? '');
    $ai_brain_used  = trim($_POST['ai_brain_used'] ?? '');
    $support_days   = (int)($_POST['support_days'] ?? 0);
    $status         = trim($_POST['status'] ?? 'active');

    // Admin-exclusive tracking metrics inputs
    


    // Validation checks
    if (empty($item_name) || empty($item_slug) || $category_id <= 0 || $amount < 0) {
        $error_msg = "Critical architecture elements missing. Verify names, slugs, categorizations, and validation values.";
    } else {
        // File upload setup mapping properties configurations fallback arrays
        $images = [
            'feature_image' => $item['feature_image'],
            'screenshot_2'  => $item['screenshot_2'],
            'screenshot_3'  => $item['screenshot_3']
        ];
        $item_zip_file = $item['item_zip_file'] ?? null;

        $upload_dir = __DIR__ . '/../uploads/';
        if (!is_dir($upload_dir)) {
            mkdir($upload_dir, 0755, true);
        }

        foreach (['feature_image', 'screenshot_2', 'screenshot_3'] as $file_input) {
            if (isset($_FILES[$file_input]) && $_FILES[$file_input]['error'] === UPLOAD_ERR_OK) {
                $file_tmp   = $_FILES[$file_input]['tmp_name'];
                $file_name  = time() . '_' . bin2hex(random_bytes(4)) . '_' . basename($_FILES[$file_input]['name']);
                $target_file = $upload_dir . $file_name;

                if (move_uploaded_file($file_tmp, $target_file)) {
                    $images[$file_input] = 'uploads/' . $file_name;
                }
            }
        }
        // Delete existing ZIP
        if (isset($_POST['delete_zip']) && $_POST['delete_zip'] == '1') {

            if (!empty($item_zip_file)) {

                $fullPath = __DIR__ . '/../' . $item_zip_file;

                if (file_exists($fullPath)) {
                    @unlink($fullPath);
                }
            }

            $item_zip_file = null;
        }


        // Upload new ZIP
        if (isset($_FILES['item_zip_file']) && $_FILES['item_zip_file']['error'] === UPLOAD_ERR_OK) {

            $ext = strtolower(pathinfo($_FILES['item_zip_file']['name'], PATHINFO_EXTENSION));

            if ($ext === 'zip') {

                $zipDir = __DIR__ . '/../uploads/products/zips/';

                if (!is_dir($zipDir)) {
                    mkdir($zipDir, 0755, true);
                }

                // delete old zip
                if (!empty($item_zip_file)) {

                    $oldZip = __DIR__ . '/../' . $item_zip_file;

                    if (file_exists($oldZip)) {
                        @unlink($oldZip);
                    }
                }

                $zipName = time() . '_' .
                    preg_replace('/[^a-zA-Z0-9._-]/', '_', $_FILES['item_zip_file']['name']);

                move_uploaded_file(
                    $_FILES['item_zip_file']['tmp_name'],
                    $zipDir . $zipName
                );

                $item_zip_file = 'uploads/products/zips/' . $zipName;
            }
        }

        try {
            // Update transaction execution pipeline mapping all structural columns explicitly
            $updateStmt = $pdo->prepare("
                UPDATE items SET 
                    item_name = ?, 
                    item_slug = ?, 
                    category_id = ?, 
                    amount = ?, 
                    item_details = ?, 
                    feature_image = ?, 
                    screenshot_2 = ?, 
                    screenshot_3 = ?, 
                    item_zip_file = ?,
                    video_url = ?, 
                    demo_url = ?, 
                    files_included = ?, 
                    ai_brain_used = ?, 
                    support_days = ?, 
                    status = ? 
                WHERE id = ?
            ");

            $updateStmt->execute([
                $item_name,
                $item_slug,
                $category_id,
                $amount,
                $item_details,
                $images['feature_image'],
                $images['screenshot_2'],
                $images['screenshot_3'],
                $item_zip_file,
                $video_url,
                $demo_url,
                $files_included,
                $ai_brain_used,
                $support_days,
                $status,
                $item_id
            ]);

            $success_msg = "Platform inventory item configuration registry records synchronized successfully.";

            // Refresh local row tracking data mapping state properties values
            $stmt->execute([$item_id]);
            $item = $stmt->fetch();
        } catch (Exception $e) {
            $error_msg = "Database Synchronization Interrupt Fault: " . $e->getMessage();
        }
    }
}

// CodeCanyon Production Standard Guideline: Inject standard secure UI Header Wrapper layout component
require_once __DIR__ . '/../sections/header.php';
?>

<body class="bg-nftDark text-white antialiased overflow-x-hidden">

    <?php include_once __DIR__ . '/admin-sidebar.php'; ?>

    <main class="lg:ml-64 min-h-screen pt-24 lg:pt-10 pb-16 px-4 sm:px-6 lg:px-8">
        <div class="max-w-5xl mx-auto space-y-8">

            <div class="flex items-center space-x-2 text-xs font-bold uppercase tracking-widest text-nftTextGray">
                <a href="admin-dashboard.php" class="hover:text-nftAccentCyan transition-colors">Dashboard</a>
                <span>/</span>
                <span class="text-nftAccentPurple">Modify Catalog Element</span>
            </div>

            <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between border-b border-slate-900/60 pb-6 gap-4">
                <div>
                    <h1 class="text-3xl font-extrabold tracking-tight text-white">Edit Platform Item</h1>
                    <p class="text-sm text-nftTextGray mt-1">Overriding administrative console controls for product configuration nodes uploaded by: <span class="text-nftAccentCyan font-semibold"><?php echo htmlspecialchars($item['seller_name'] ?? 'System/Internal'); ?></span></p>
                </div>
                <a href="admin-dashboard.php" class="bg-slate-900 hover:bg-slate-800 border border-slate-800 text-slate-400 hover:text-white px-4 py-2.5 rounded-xl text-xs font-bold tracking-wider uppercase transition-all shadow-sm">
                    &larr; Return to Inventory
                </a>
            </div>

            <?php if (!empty($error_msg)): ?>
                <div class="p-4 bg-rose-500/10 border border-rose-500/20 rounded-xl text-xs font-mono text-rose-400 flex items-center gap-2.5 shadow-md">
                    <i class="fa-solid fa-triangle-exclamation text-base"></i> <?php echo $error_msg; ?>
                </div>
            <?php endif; ?>

            <?php if (!empty($success_msg)): ?>
                <div class="p-4 bg-emerald-500/10 border border-emerald-500/20 rounded-xl text-xs font-medium text-emerald-400 flex items-center gap-2.5 shadow-md">
                    <i class="fa-solid fa-circle-check text-base"></i> <?php echo $success_msg; ?>
                </div>
            <?php endif; ?>

            <form method="POST" enctype="multipart/form-data" class="space-y-6">

                <div class="grid grid-cols-1 md:grid-cols-3 gap-6">

                    <div class="md:col-span-2 space-y-6">
                        <div class="glass-card p-6 rounded-2xl border border-slate-800/80 space-y-5 shadow-lg relative overflow-hidden">
                            <h3 class="text-sm font-bold uppercase text-nftAccentCyan tracking-wider border-b border-slate-900 pb-3">// Base Identification Metadata</h3>

                            <div class="space-y-2">
                                <label class="text-xs font-bold text-slate-400 uppercase tracking-wider block">Product Title Asset Name</label>
                                <input type="text" name="item_name" value="<?php echo htmlspecialchars($item['item_name']); ?>" class="w-full bg-slate-950/80 border border-slate-900 focus:border-nftAccentCyan focus:outline-none rounded-xl px-4 py-3 text-xs font-medium transition-colors" required>
                            </div>

                            <div class="space-y-2">
                                <label class="text-xs font-bold text-slate-400 uppercase tracking-wider block">Ecosystem Anchor URL Slug Link Handle</label>
                                <input type="text" name="item_slug" value="<?php echo htmlspecialchars($item['item_slug']); ?>" class="w-full bg-slate-950/80 border border-slate-900 focus:border-nftAccentCyan focus:outline-none rounded-xl px-4 py-3 text-xs font-mono transition-colors" required>
                            </div>

                            <div class="space-y-2">
                                <label class="text-xs font-bold text-slate-400 uppercase tracking-wider block">Deep Feature Overview Details Specifications</label>
                                <textarea name="item_details" rows="8" class="w-full bg-slate-950/80 border border-slate-900 focus:border-nftAccentCyan focus:outline-none rounded-xl px-4 py-3 text-xs font-medium transition-colors" required><?php echo htmlspecialchars($item['item_details']); ?></textarea>
                            </div>
                        </div>

                        <div class="glass-card p-6 rounded-2xl border border-slate-800/80 space-y-5 shadow-lg">
                            <h3 class="text-sm font-bold uppercase text-nftAccentPurple tracking-wider border-b border-slate-900 pb-3">// Platform Integration Assets Interfaces Links</h3>

                            <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
                                <div class="space-y-2">
                                    <label class="text-xs font-bold text-slate-400 uppercase tracking-wider block">Live Frame Demo Web URL</label>
                                    <input type="url" name="demo_url" value="<?php echo htmlspecialchars($item['demo_url'] ?? ''); ?>" class="w-full bg-slate-950/80 border border-slate-900 focus:border-nftAccentCyan focus:outline-none rounded-xl px-4 py-3 text-xs transition-colors" placeholder="https://">
                                </div>
                                <div class="space-y-2">
                                    <label class="text-xs font-bold text-slate-400 uppercase tracking-wider block">Video Demonstration Walkthrough Link</label>
                                    <input type="url" name="video_url" value="<?php echo htmlspecialchars($item['video_url'] ?? ''); ?>" class="w-full bg-slate-950/80 border border-slate-900 focus:border-nftAccentCyan focus:outline-none rounded-xl px-4 py-3 text-xs transition-colors" placeholder="https://">
                                </div>
                            </div>

                            <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
                                <div class="space-y-2">
                                    <label class="text-xs font-bold text-slate-400 uppercase tracking-wider block">Files Packages Included Catalog List</label>
                                    <input type="text" name="files_included" value="<?php echo htmlspecialchars($item['files_included'] ?? ''); ?>" class="w-full bg-slate-950/80 border border-slate-900 focus:border-nftAccentCyan focus:outline-none rounded-xl px-4 py-3 text-xs transition-colors" placeholder="PHP, JavaScript, SQL, ZIP Archive">
                                </div>
                                <div class="space-y-2">
                                    <label class="text-xs font-bold text-slate-400 uppercase tracking-wider block">AI Core Model/Brain Engine Blueprint Used</label>
                                    <input type="text" name="ai_brain_used" value="<?php echo htmlspecialchars($item['ai_brain_used'] ?? ''); ?>" class="w-full bg-slate-950/80 border border-slate-900 focus:border-nftAccentCyan focus:outline-none rounded-xl px-4 py-3 text-xs transition-colors" placeholder="GPT-4o, Claude 3.5 Sonnet Framework Node">
                                </div>
                            </div>
                        </div>

                        <div class="glass-card p-6 rounded-2xl border border-slate-800/80 space-y-5 shadow-lg">
                            <h3 class="text-sm font-bold uppercase text-slate-400 tracking-wider border-b border-slate-900 pb-3">// Repository Assets Image Overrides Visual Modules</h3>

                            <div class="flex flex-col sm:flex-row items-start sm:items-center gap-4 p-4 bg-slate-950/50 border border-slate-900 rounded-xl">
                                <div class="w-20 h-16 rounded-lg bg-slate-900 border border-slate-800 overflow-hidden shrink-0 flex items-center justify-center shadow-inner">
                                    <img src="<?php echo !empty($item['feature_image']) ? '../' . $item['feature_image'] : '../assets/img/placeholder.png'; ?>" class="w-full h-full object-cover">
                                </div>
                                <div class="space-y-1.5 w-full">
                                    <label class="text-xs font-bold text-slate-400 uppercase tracking-wider block">Item Cover Feature Image Thumbnail Override</label>
                                    <input type="file" name="feature_image" class="text-xs font-mono text-slate-500 file:mr-4 file:py-1.5 file:px-3 file:rounded-md file:border-0 file:bg-slate-900 file:text-nftAccentCyan file:font-bold hover:file:bg-slate-800 file:text-[10px] file:uppercase cursor-pointer">
                                </div>
                            </div>

                            <div class="flex flex-col sm:flex-row items-start sm:items-center gap-4 p-4 bg-slate-950/50 border border-slate-900 rounded-xl">
                                <div class="w-20 h-16 rounded-lg bg-slate-900 border border-slate-800 overflow-hidden shrink-0 flex items-center justify-center shadow-inner">
                                    <img src="<?php echo !empty($item['screenshot_2']) ? '../' . $item['screenshot_2'] : '../assets/img/placeholder.png'; ?>" class="w-full h-full object-cover">
                                </div>
                                <div class="space-y-1.5 w-full">
                                    <label class="text-xs font-bold text-slate-400 uppercase tracking-wider block">Ecosystem Screenshot View Panel Node 2</label>
                                    <input type="file" name="screenshot_2" class="text-xs font-mono text-slate-500 file:mr-4 file:py-1.5 file:px-3 file:rounded-md file:border-0 file:bg-slate-900 file:text-nftAccentCyan file:font-bold hover:file:bg-slate-800 file:text-[10px] file:uppercase cursor-pointer">
                                </div>
                            </div>

                            <div class="flex flex-col sm:flex-row items-start sm:items-center gap-4 p-4 bg-slate-950/50 border border-slate-900 rounded-xl">
                                <div class="w-20 h-16 rounded-lg bg-slate-900 border border-slate-800 overflow-hidden shrink-0 flex items-center justify-center shadow-inner">
                                    <img src="<?php echo !empty($item['screenshot_3']) ? '../' . $item['screenshot_3'] : '../assets/img/placeholder.png'; ?>" class="w-full h-full object-cover">
                                </div>
                                <div class="space-y-1.5 w-full">
                                    <label class="text-xs font-bold text-slate-400 uppercase tracking-wider block">Ecosystem Screenshot View Panel Node 3</label>
                                    <input type="file" name="screenshot_3" class="text-xs font-mono text-slate-500 file:mr-4 file:py-1.5 file:px-3 file:rounded-md file:border-0 file:bg-slate-900 file:text-nftAccentCyan file:font-bold hover:file:bg-slate-800 file:text-[10px] file:uppercase cursor-pointer">
                                </div>
                            </div>
                            <div class="glass-card p-6 rounded-2xl border border-slate-800/80 space-y-5 shadow-lg">

                                <h3 class="text-sm font-bold uppercase text-nftAccentCyan tracking-wider border-b border-slate-900 pb-3">
                                    // Product Download Package
                                </h3>

                                <?php if (!empty($item['item_zip_file'])): ?>

                                    <div class="bg-slate-950/50 border border-slate-900 rounded-xl p-4">

                                        <div class="flex items-center justify-between gap-4">

                                            <div>

                                                <div class="text-xs text-slate-400 mb-1">
                                                    Current ZIP Package
                                                </div>

                                                <a
                                                    href="../<?php echo htmlspecialchars($item['item_zip_file']); ?>"
                                                    download
                                                    class="text-nftAccentCyan hover:text-white text-sm font-semibold break-all">

                                                    <?php echo basename($item['item_zip_file']); ?>

                                                </a>

                                            </div>

                                            <label class="flex items-center gap-2 text-rose-400 text-xs font-semibold">

                                                <input
                                                    type="checkbox"
                                                    name="delete_zip"
                                                    value="1">

                                                Delete ZIP

                                            </label>

                                        </div>

                                    </div>

                                <?php else: ?>

                                    <div class="bg-slate-950/50 border border-slate-900 rounded-xl p-4 text-slate-500 text-xs">
                                        No ZIP package uploaded.
                                    </div>

                                <?php endif; ?>

                                <div>

                                    <label class="block text-xs font-bold text-slate-400 uppercase tracking-wider mb-2">

                                        Upload New ZIP File

                                    </label>

                                    <input
                                        type="file"
                                        name="item_zip_file"
                                        accept=".zip"
                                        class="text-xs font-mono text-slate-500
            file:mr-4
            file:py-2
            file:px-4
            file:rounded-md
            file:border-0
            file:bg-slate-900
            file:text-nftAccentCyan
            file:font-bold">

                                </div>

                            </div>
                        </div>
                    </div>

                    <div class="space-y-6">

                        <div class="glass-card p-6 rounded-2xl border border-slate-800/80 space-y-4 shadow-lg bg-gradient-to-b from-slate-950/20 to-slate-950/70">
                            <h3 class="text-sm font-bold uppercase text-emerald-400 tracking-wider border-b border-slate-900 pb-3">// Market Monetization Controls</h3>

                            <div class="space-y-2">
                                <label class="text-xs font-bold text-slate-400 uppercase tracking-wider block">License Baseline Valuation Amount (<?php echo htmlspecialchars(get_site_currency(), ENT_QUOTES, 'UTF-8'); ?>)</label>
                                <div class="relative rounded-xl shadow-sm">
                                    <span class="absolute inset-y-0 left-0 flex items-center pl-4 font-mono text-emerald-500 text-xs font-bold"><?php echo htmlspecialchars(currency_symbol(), ENT_QUOTES, 'UTF-8'); ?></span>
                                    <input type="number" step="0.01" min="0.00" name="amount" value="<?php echo htmlspecialchars($item['amount']); ?>" class="w-full bg-slate-950 text-white font-mono font-bold text-xs pl-8 pr-4 py-3.5 rounded-xl border border-slate-900 focus:outline-none focus:border-emerald-500 transition-colors" required>
                                </div>
                            </div>

                            <div class="space-y-2">
                                <label class="text-xs font-bold text-slate-400 uppercase tracking-wider block">Ecosystem Market Classification Group</label>
                                <select name="category_id" class="w-full bg-slate-950 text-white font-medium text-xs px-4 py-3 rounded-xl border border-slate-900 focus:outline-none focus:border-nftAccentCyan transition-all" required>
                                    <option value="">-- Choose Target Classification --</option>
                                    <?php foreach ($categories as $cat): ?>
                                        <option value="<?php echo $cat['id']; ?>" <?php echo ((int)$item['category_id'] === (int)$cat['id']) ? 'selected' : ''; ?>>
                                            <?php echo htmlspecialchars($cat['category_name']); ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>

                            <div class="space-y-2">
                                <label class="text-xs font-bold text-slate-400 uppercase tracking-wider block">Included Support Time-Window Matrix Length</label>
                                <div class="relative rounded-xl shadow-sm">
                                    <input type="number" min="0" name="support_days" value="<?php echo htmlspecialchars($item['support_days']); ?>" class="w-full bg-slate-950 text-white font-mono font-bold text-xs px-4 py-3 rounded-xl border border-slate-900 focus:outline-none focus:border-nftAccentCyan transition-colors" required>
                                    <span class="absolute inset-y-0 right-0 flex items-center pr-4 font-sans text-slate-500 text-[10px] font-bold uppercase tracking-wider pointer-events-none">Days Included</span>
                                </div>
                            </div>
                        </div>

                        <div class="glass-card p-6 rounded-2xl border border-slate-800/80 space-y-4 shadow-lg bg-gradient-to-b from-slate-950/20 to-slate-950/70 relative">
                            <div class="absolute top-4 right-4 text-[10px] bg-nftAccentPurple/10 text-nftAccentPurple px-2 py-0.5 rounded-md font-extrabold uppercase font-mono tracking-wider border border-nftAccentPurple/20">Admin Only</div>
                            <h3 class="text-sm font-bold uppercase text-nftAccentPurple tracking-wider border-b border-slate-900 pb-3">// Analytics Metrics Overrides</h3>

                        </div>

                        <div class="glass-card p-6 rounded-2xl border border-slate-800/80 space-y-4 shadow-lg">
                            <h3 class="text-sm font-bold uppercase text-slate-400 tracking-wider border-b border-slate-900 pb-3">// Market Operational Status</h3>

                            <div class="space-y-2">
                                <label class="text-xs font-bold text-slate-400 uppercase tracking-wider block">Marketplace Status Flag Visibility</label>
                                <select name="status" class="w-full bg-slate-950 text-white font-bold text-xs px-4 py-3 rounded-xl border border-slate-900 focus:outline-none focus:border-nftAccentCyan transition-all" required>
                                    <option value="active" <?php echo ($item['status'] === 'active') ? 'selected' : ''; ?>>ACTIVE / VERIFIED LIVE</option>
                                    <option value="pending" <?php echo ($item['status'] === 'pending') ? 'selected' : ''; ?>>PENDING REVIEW</option>
                                    <option value="suspended" <?php echo ($item['status'] === 'suspended') ? 'selected' : ''; ?>>SUSPENDED / INACTIVE LOCKOUT</option>
                                </select>
                            </div>

                            <div class="pt-2">
                                <button type="submit" class="w-full btn-gradient py-3.5 px-4 rounded-xl text-xs font-bold uppercase tracking-widest text-white transition-all shadow-md active:scale-[0.99]">
                                    <i class="fa-solid fa-cloud-arrow-up mr-2 text-xs"></i> Synchronize Configuration
                                </button>
                            </div>
                        </div>

                    </div>
                </div>
            </form>

        </div>
    </main>

</body>

</html>
