<?php
/**
 * Agentic Square - Premium Seller Dashboard: Profile Configuration
 * Path: seller/profile-settings.php
 */

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

// SECURITY ACCESS GUARD
if (session_status() === PHP_SESSION_NONE) session_start();
if (!isset($_SESSION['user_id'])) {
    header('Location: ../login.php');
    exit;
}

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

// HANDLE DATA UPDATES
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // 1. Fetch current data to preserve existing image if no new one is uploaded
    $stmt = $pdo->prepare("SELECT profile_picture FROM sellers WHERE user_id = ?");
    $stmt->execute([$user_id]);
    $current_data = $stmt->fetch(PDO::FETCH_ASSOC);
    $profile_picture = $current_data['profile_picture'] ?? '';

    // 2. Handle File Upload
    if (!empty($_FILES['profile_picture']['name'])) {
        $upload_dir = '../assets/uploads/sellers/';
        if (!is_dir($upload_dir)) mkdir($upload_dir, 0755, true);
        
        $file_ext = pathinfo($_FILES['profile_picture']['name'], PATHINFO_EXTENSION);
        $new_filename = 'seller_' . $user_id . '_' . time() . '.' . $file_ext;
        
        if (move_uploaded_file($_FILES['profile_picture']['tmp_name'], $upload_dir . $new_filename)) {
            $profile_picture = 'assets/uploads/sellers/' . $new_filename;
        }
    }

    // 3. Update Database (9 Parameters total)
    $sql = "UPDATE sellers SET 
            seller_name = ?, 
            profile_picture = ?, 
            about = ?, 
            address = ?, 
            city = ?, 
            state = ?, 
            postcode = ?, 
            country = ?, 
            updated_at = NOW() 
            WHERE user_id = ?";

    $stmt = $pdo->prepare($sql);
    $stmt->execute([
        $_POST['seller_name'] ?? '',
        $profile_picture,
        $_POST['about'] ?? '',
        $_POST['address'] ?? '',
        $_POST['city'] ?? '',
        $_POST['state'] ?? '',
        $_POST['postcode'] ?? '',
        $_POST['country'] ?? '',
        $user_id
    ]);
    
    $message = "Profile and avatar updated successfully.";
}

// FETCH LATEST DATA
$stmt = $pdo->prepare("SELECT * FROM sellers WHERE user_id = ?");
$stmt->execute([$user_id]);
$seller = $stmt->fetch(PDO::FETCH_ASSOC);

// COUNTRY LIST
$countries = ["Afghanistan", "Albania", "Algeria", "Andorra", "Angola", "Antigua and Barbuda", "Argentina", "Armenia", "Australia", "Austria", "Azerbaijan", "Bahamas", "Bahrain", "Bangladesh", "Barbados", "Belarus", "Belgium", "Belize", "Benin", "Bhutan", "Bolivia", "Bosnia and Herzegovina", "Botswana", "Brazil", "Brunei", "Bulgaria", "Burkina Faso", "Burundi", "Cabo Verde", "Cambodia", "Cameroon", "Canada", "Central African Republic", "Chad", "Chile", "China", "Colombia", "Comoros", "Congo", "Costa Rica", "Croatia", "Cuba", "Cyprus", "Czechia", "Denmark", "Djibouti", "Dominica", "Dominican Republic", "Ecuador", "Egypt", "El Salvador", "Equatorial Guinea", "Eritrea", "Estonia", "Eswatini", "Ethiopia", "Fiji", "Finland", "France", "Gabon", "Gambia", "Georgia", "Germany", "Ghana", "Greece", "Grenada", "Guatemala", "Guinea", "Guinea-Bissau", "Guyana", "Haiti", "Honduras", "Hungary", "Iceland", "India", "Indonesia", "Iran", "Iraq", "Ireland", "Israel", "Italy", "Jamaica", "Japan", "Jordan", "Kazakhstan", "Kenya", "Kiribati", "Korea, North", "Korea, South", "Kuwait", "Kyrgyzstan", "Laos", "Latvia", "Lebanon", "Lesotho", "Liberia", "Libya", "Liechtenstein", "Lithuania", "Luxembourg", "Madagascar", "Malawi", "Malaysia", "Maldives", "Mali", "Malta", "Marshall Islands", "Mauritania", "Mauritius", "Mexico", "Micronesia", "Moldova", "Monaco", "Mongolia", "Montenegro", "Morocco", "Mozambique", "Myanmar", "Namibia", "Nauru", "Nepal", "Netherlands", "New Zealand", "Nicaragua", "Niger", "Nigeria", "North Macedonia", "Norway", "Oman", "Pakistan", "Palau", "Panama", "Papua New Guinea", "Paraguay", "Peru", "Philippines", "Poland", "Portugal", "Qatar", "Romania", "Russia", "Rwanda", "Saint Kitts and Nevis", "Saint Lucia", "Saint Vincent and the Grenadines", "Samoa", "San Marino", "Sao Tome and Principe", "Saudi Arabia", "Senegal", "Serbia", "Seychelles", "Sierra Leone", "Singapore", "Slovakia", "Slovenia", "Solomon Islands", "Somalia", "South Africa", "Spain", "Sri Lanka", "Sudan", "Suriname", "Sweden", "Switzerland", "Syria", "Taiwan", "Tajikistan", "Tanzania", "Thailand", "Timor-Leste", "Togo", "Tonga", "Trinidad and Tobago", "Tunisia", "Turkey", "Turkmenistan", "Tuvalu", "Uganda", "Ukraine", "United Arab Emirates", "United Kingdom", "United States", "Uruguay", "Uzbekistan", "Vanuatu", "Vatican City", "Venezuela", "Vietnam", "Yemen", "Zambia", "Zimbabwe"];

require_once __DIR__ . '/../sections/header.php';
?>

<body class="bg-nftDark text-white antialiased">
    <?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 class="border-b border-slate-900/60 pb-6">
                <h1 class="text-3xl font-extrabold tracking-tight text-white">Profile Settings</h1>
            </div>

            <?php if($message): ?>
                <div class="bg-emerald-500/10 border border-emerald-500/20 text-emerald-400 p-4 rounded-xl text-xs font-bold font-mono">
                    <i class="fa-solid fa-circle-check mr-2"></i> <?php echo $message; ?>
                </div>
            <?php endif; ?>

            <form method="POST" enctype="multipart/form-data" class="glass-card p-8 rounded-2xl border border-slate-800/80 bg-slate-950/20 space-y-6">
                <div class="flex items-center gap-6 pb-4 border-b border-slate-900/50">
                    <div class="w-20 h-20 rounded-full border-2 border-slate-800 overflow-hidden bg-slate-900">
                        <img src="<?php echo !empty($seller['profile_picture']) ? '../' . $seller['profile_picture'] : '../assets/img/placeholder.png'; ?>" class="w-full h-full object-cover">
                    </div>
                    <div>
                        <label class="block text-[10px] font-bold uppercase text-nftTextGray mb-2">Profile Avatar</label>
                        <input type="file" name="profile_picture" class="block w-full text-xs text-slate-400 file:mr-4 file:py-2 file:px-4 file:rounded-lg file:border-0 file:text-xs file:font-bold file:bg-slate-900 file:text-white hover:file:bg-slate-800 cursor-pointer">
                    </div>
                </div>

                <div class="grid md:grid-cols-2 gap-6">
                    <div>
                        <label class="block text-[10px] font-bold uppercase text-nftTextGray mb-2">Full Business Name</label>
                        <input type="text" name="seller_name" value="<?php echo htmlspecialchars($seller['seller_name'] ?? ''); ?>" class="w-full bg-slate-950/80 border border-slate-900 rounded-xl p-3.5 text-sm text-white focus:border-nftAccentCyan outline-none">
                    </div>
                    <div>
                        <label class="block text-[10px] font-bold uppercase text-nftTextGray mb-2">Operational Country</label>
                        <select name="country" class="w-full bg-slate-950/80 border border-slate-900 rounded-xl p-3.5 text-sm text-white focus:border-nftAccentCyan outline-none">
                            <?php foreach($countries as $c): ?>
                                <option value="<?php echo $c; ?>" <?php echo ($seller['country'] == $c) ? 'selected' : ''; ?>><?php echo $c; ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>

                <div>
                    <label class="block text-[10px] font-bold uppercase text-nftTextGray mb-2">Street Address</label>
                    <input type="text" name="address" value="<?php echo htmlspecialchars($seller['address'] ?? ''); ?>" class="w-full bg-slate-950/80 border border-slate-900 rounded-xl p-3.5 text-sm text-white outline-none">
                </div>

                <div>
                    <label class="block text-[10px] font-bold uppercase text-nftTextGray mb-2">About / Business Bio</label>
                    <textarea name="about" rows="4" class="w-full bg-slate-950/80 border border-slate-900 rounded-xl p-3.5 text-sm text-white focus:border-nftAccentCyan outline-none"><?php echo htmlspecialchars($seller['about'] ?? ''); ?></textarea>
                </div>

                <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                    <input type="text" name="city" placeholder="City" value="<?php echo htmlspecialchars($seller['city'] ?? ''); ?>" class="w-full bg-slate-950/80 border border-slate-900 rounded-xl p-3.5 text-sm text-white outline-none">
                    <input type="text" name="state" placeholder="State" value="<?php echo htmlspecialchars($seller['state'] ?? ''); ?>" class="w-full bg-slate-950/80 border border-slate-900 rounded-xl p-3.5 text-sm text-white outline-none">
                    <input type="text" name="postcode" placeholder="Postcode" value="<?php echo htmlspecialchars($seller['postcode'] ?? ''); ?>" class="w-full bg-slate-950/80 border border-slate-900 rounded-xl p-3.5 text-sm text-white outline-none">
                </div>

                <button type="submit" class="w-full md:w-auto bg-gradient-to-r from-nftAccentCyan to-nftAccentPurple text-slate-950 font-black tracking-wide text-xs px-8 py-4 rounded-xl shadow-lg hover:opacity-90 transition-all">
                    Commit Profile Updates
                </button>
            </form>
        </div>
    </main>
</body>
</html>