<?php
/**
 * Agentic Square - Premium Seller Profile Portal
 * CodeCanyon Execution Core Template Architecture
 */

require_once __DIR__ . '/../config/config.php';

// Access Control Interceptor Guard
if (!isset($_SESSION['user_id']) || !isset($_SESSION['user_role']) || $_SESSION['user_role'] !== 'seller') {
    header('Location: ../login.php');
    exit;
}

$user_id = (int)$_SESSION['user_id'];
$success_msg = $error_msg = "";

// Pull current seller matrix record layer if it exists
$stmt = $pdo->prepare("SELECT * FROM sellers WHERE user_id = ? LIMIT 1");
$stmt->execute([$user_id]);
$seller = $stmt->fetch();

function generateSlug($string) {
    $string = strtolower($string);
    $string = preg_replace('/[^a-z0-9\s-]/', '', $string);
    $string = preg_replace('/[\s-]+/', ' ', $string);
    $string = preg_replace('/\s/', '-', $string);
    return trim($string, '-');
}

// Dynamic extraction fallback: Fetch original account email directly from users authentication table
$userStmt = $pdo->prepare("SELECT email FROM users WHERE id = ? LIMIT 1");
$userStmt->execute([$user_id]);
$userAccount = $userStmt->fetch();
$defaultAccountEmail = $userAccount ? $userAccount['email'] : '';

// Establish display email: prioritize custom merchant email, fall back to master login email
$currentDisplayEmail = !empty($seller['email']) ? $seller['email'] : $defaultAccountEmail;

// Form Transaction Execution Hook
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $seller_name = trim($_POST['seller_name'] ?? '');
    $seller_slug = generateSlug($seller_name);
    $email       = trim($_POST['email'] ?? '');
    $address     = trim($_POST['address'] ?? '');
    $city        = trim($_POST['city'] ?? '');
    $state       = trim($_POST['state'] ?? '');
    $postcode    = trim($_POST['postcode'] ?? '');
    $country     = trim($_POST['country'] ?? '');
    $about       = trim($_POST['about'] ?? '');

    if (empty($seller_name) || empty($email) || empty($address) || empty($city) || empty($country)) {
        $error_msg = "Please populate all foundational location and branding parameters.";
    } else {
        /**
         * IMAGE PROCESSING CORE PIPELINE
         * Upload Destination Target: marketplace/uploads/sellers/
         */
        $profile_picture = !empty($seller['profile_picture']) ? $seller['profile_picture'] : 'uploads/sellers/default-avatar.png';
        
        if (isset($_FILES['profile_pic']) && $_FILES['profile_pic']['error'] === UPLOAD_ERR_OK) {
            $fileTmpPath = $_FILES['profile_pic']['tmp_name'];
            $originalName = $_FILES['profile_pic']['name'];
            
            // Clean up name string format to safely map file extensions
            $cleanFileName = time() . '_' . preg_replace("/[^a-zA-Z0-9.]/", "_", $originalName);
            
            // Path targeted relative to execution directory root structure
            $uploadDir = __DIR__ . '/../uploads/sellers/';
            
            // Verify and auto-initialize directory tree nodes safely if unallocated
            if (!is_dir($uploadDir)) {
                mkdir($uploadDir, 0755, true);
            }
            
            if (move_uploaded_file($fileTmpPath, $uploadDir . $cleanFileName)) {
                // Save database record with path reference matching web root context
                $profile_picture = 'uploads/sellers/' . $cleanFileName;
            } else {
                $error_msg = "Warning: Failed to execute system folder moves on graphic payload binaries.";
            }
        }

        if (empty($error_msg)) {
            if ($seller) {
                // Matrix Layer Mutation Update
                $updateStmt = $pdo->prepare("UPDATE sellers SET seller_name = ?, seller_slug = ?, profile_picture = ?, address = ?, city = ?, state = ?, postcode = ?, country = ?, about = ?, email = ? WHERE user_id = ?");
                $updateStmt->execute([$seller_name, $seller_slug, $profile_picture, $address, $city, $state, $postcode, $country, $about, $email, $user_id]);
                $success_msg = "Merchant Identity Engine Refreshed Successfully!";
            } else {
                // Registry Initialization Creation
                $insertStmt = $pdo->prepare("
    INSERT INTO sellers 
    (user_id, seller_name, seller_slug, profile_picture, address, city, state, postcode, country, about, email, current_balance)
    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 0.00)
");
                $insertStmt->execute([$user_id, $seller_name, $seller_slug, $profile_picture, $address, $city, $state, $postcode, $country, $about, $email]);
                $success_msg = "Storefront Configured! Your asset release parameters are online.";
            }
            
            // Reload parameters securely
            $stmt = $pdo->prepare("SELECT * FROM sellers WHERE user_id = ? LIMIT 1");
            $stmt->execute([$user_id]);
            $seller = $stmt->fetch();
            $currentDisplayEmail = !empty($seller['email']) ? $seller['email'] : $defaultAccountEmail;
        }
    }
}

require_once __DIR__ . '/../sections/header.php';
?>
<body class="bg-nftDark text-white antialiased overflow-x-hidden">
    <?php include_once __DIR__ . '/seller-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-4xl mx-auto space-y-8">
            <div>
                <span class="text-xs font-bold tracking-widest text-nftAccentPurple uppercase block mb-1">// Security Verified Storefront Layer</span>
                <h1 class="text-3xl font-extrabold tracking-tight text-white">Merchant Profile Matrix</h1>
                <p class="text-sm text-nftTextGray mt-1">Keep your corporate distribution location contexts and client payout parameters updated.</p>
            </div>

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

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

            <form action="" method="POST" enctype="multipart/form-data" class="glass-card p-8 rounded-3xl border border-slate-800/80 space-y-6 relative">
                <div class="grid grid-cols-1 md:grid-cols-3 gap-6 items-center border-b border-slate-900/60 pb-6">
                    <div class="flex flex-col items-center space-y-3">
                        <?php 
                            // Render image from profile path location or serve system avatar placeholder
                            $avatarSource = (!empty($seller['profile_picture']) && file_exists(__DIR__ . '/../' . $seller['profile_picture'])) 
                                ? '../' . $seller['profile_picture'] 
                                : 'https://images.unsplash.com/photo-1618005182384-a83a8bd57fbe?w=150';
                        ?>
                        <img src="<?php echo $avatarSource; ?>" class="w-24 h-24 rounded-2xl object-cover border-2 border-nftAccentCyan shadow-xl" alt="Store Avatar">
                        <label class="cursor-pointer bg-slate-900 border border-slate-800 hover:border-nftAccentCyan text-[11px] font-bold px-3 py-1.5 rounded-lg transition-colors">
                            <i class="fa-solid fa-camera mr-1"></i> Replace Image
                            <input type="file" name="profile_pic" class="hidden" accept="image/*">
                        </label>
                    </div>
                    <div class="md:col-span-2 space-y-4">
                        <div>
                            <label class="block text-[11px] font-bold text-nftTextGray uppercase tracking-wider mb-2">Public Store Name / Handle</label>
                            <input type="text" name="seller_name" required value="<?php echo htmlspecialchars($seller['seller_name'] ?? ''); ?>" class="w-full bg-slate-950/80 border border-slate-800/80 rounded-xl px-4 py-3 text-sm text-white focus:outline-none focus:border-nftAccentCyan transition-colors" placeholder="e.g. Pixels Studio AI">
                        </div>
                        <div>
                            <label class="block text-[11px] font-bold text-nftTextGray uppercase tracking-wider mb-2">Merchant Operations Email Address</label>
                            <input type="email" name="email" required value="<?php echo htmlspecialchars($currentDisplayEmail); ?>" class="w-full bg-slate-950/80 border border-slate-800/80 rounded-xl px-4 py-3 text-sm text-white focus:outline-none focus:border-nftAccentCyan transition-colors" placeholder="merchant@agenticsquare.com">
                        </div>
                    </div>
                </div>

                <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <div class="md:col-span-2">
                        <label class="block text-[11px] font-bold text-nftTextGray uppercase tracking-wider mb-2">Corporate Headquarters / Office Address</label>
                        <input type="text" name="address" required value="<?php echo htmlspecialchars($seller['address'] ?? ''); ?>" class="w-full bg-slate-950/80 border border-slate-800/80 rounded-xl px-4 py-3 text-sm text-white focus:outline-none focus:border-nftAccentCyan transition-colors" placeholder="Street layout address blocks">
                    </div>
                    <div>
                        <label class="block text-[11px] font-bold text-nftTextGray uppercase tracking-wider mb-2">City</label>
                        <input type="text" name="city" required value="<?php echo htmlspecialchars($seller['city'] ?? ''); ?>" class="w-full bg-slate-950/80 border border-slate-800/80 rounded-xl px-4 py-3 text-sm text-white focus:outline-none focus:border-nftAccentCyan transition-colors" placeholder="Metropolitan Core Area">
                    </div>
                    <div>
                        <label class="block text-[11px] font-bold text-nftTextGray uppercase tracking-wider mb-2">State / Region</label>
                        <input type="text" name="state" value="<?php echo htmlspecialchars($seller['state'] ?? ''); ?>" class="w-full bg-slate-950/80 border border-slate-800/80 rounded-xl px-4 py-3 text-sm text-white focus:outline-none focus:border-nftAccentCyan transition-colors" placeholder="Provincial bounds context">
                    </div>
                    <div>
                        <label class="block text-[11px] font-bold text-nftTextGray uppercase tracking-wider mb-2">Postal Code / ZIP</label>
                        <input type="text" name="postcode" value="<?php echo htmlspecialchars($seller['postcode'] ?? ''); ?>" class="w-full bg-slate-950/80 border border-slate-800/80 rounded-xl px-4 py-3 text-sm text-white focus:outline-none focus:border-nftAccentCyan transition-colors" placeholder="Route Delivery Mapping Index">
                    </div>
                    <div>
                        <label class="block text-[11px] font-bold text-nftTextGray uppercase tracking-wider mb-2">Country Domain</label>
                        <input type="text" name="country" required value="<?php echo htmlspecialchars($seller['country'] ?? ''); ?>" class="w-full bg-slate-950/80 border border-slate-800/80 rounded-xl px-4 py-3 text-sm text-white focus:outline-none focus:border-nftAccentCyan transition-colors" placeholder="Sovereign Territory Node">
                    </div>
                </div>

                <div>
                    <label class="block text-[11px] font-bold text-nftTextGray uppercase tracking-wider mb-2">Author Portfolio Biography (HTML / Markdown Compliant)</label>
                    <textarea name="about" rows="4" class="w-full bg-slate-950/80 border border-slate-800/80 rounded-xl px-4 py-3 text-sm text-white focus:outline-none focus:border-nftAccentCyan transition-colors placeholder-slate-600" placeholder="Describe your specialization engines, framework compliance patterns, and automation capabilities..."><?php echo htmlspecialchars($seller['about'] ?? ''); ?></textarea>
                </div>

                <div class="pt-4 border-t border-slate-900/60 text-right">
                    <button type="submit" class="btn-gradient px-8 py-3.5 rounded-xl font-bold tracking-widest text-xs uppercase shadow-xl transition-all text-white">
                        <i class="fa-solid fa-arrows-rotate mr-2"></i> Save Changes & Initialize
                    </button>
                </div>
            </form>
        </div>
    </main>
</body>
</html>