<?php
// --- LOGIC BLOCK ---
include 'header.php'; // Includes partner session check, DB connection, and current user data in '$user'
require_once '../includes/image-resizer.php'; 

$message = '';
// Handle form submission
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // --- Update Profile Details ---
    if (isset($_POST['update_details'])) {
        $full_name = trim(strip_tags($_POST['full_name']));
        $phone_number = trim(strip_tags($_POST['phone_number']));
        $bio = trim(strip_tags($_POST['bio']));
        $payout_details = trim($_POST['payout_details']);

        $stmt = $conn->prepare("UPDATE users SET full_name = ?, phone_number = ?, bio = ?, payout_details = ? WHERE id = ?");
        $stmt->bind_param("ssssi", $full_name, $phone_number, $bio, $payout_details, $partner_id);
        if ($stmt->execute()) {
            $_SESSION['user_name'] = $full_name; // Update session name
            $message .= '<div class="alert alert-success">Profile details updated successfully.</div>';
        }
    }
    // --- Change Password ---
    elseif (isset($_POST['change_password'])) {
        $current_password = $_POST['current_password'];
        $new_password = $_POST['new_password'];
        $confirm_password = $_POST['confirm_password'];

        if (password_verify($current_password, $user['password'])) {
            if (strlen($new_password) < 8) { $message .= '<div class="alert alert-danger">New password must be at least 8 characters.</div>'; } 
            elseif ($new_password !== $confirm_password) { $message .= '<div class="alert alert-danger">New passwords do not match.</div>'; } 
            else {
                $hashed_password = password_hash($new_password, PASSWORD_DEFAULT);
                $stmt_pass = $conn->prepare("UPDATE users SET password = ? WHERE id = ?");
                $stmt_pass->bind_param("si", $hashed_password, $partner_id);
                $stmt_pass->execute();
                $message .= '<div class="alert alert-success">Password changed successfully.</div>';
            }
        } else { $message .= '<div class="alert alert-danger">Incorrect current password.</div>'; }
    }
    // --- Profile Logo Upload ---
    elseif (isset($_POST['upload_logo'])) {
        if (isset($_FILES['profile_image']) && $_FILES['profile_image']['error'] == 0) {
            $target_dir = "../uploads/logos/";
            $target_file = $target_dir . "partner-logo-" . $partner_id . "." . strtolower(pathinfo($_FILES["profile_image"]["name"], PATHINFO_EXTENSION));
            if (resizeImage($_FILES["profile_image"]["tmp_name"], $target_file, 400, 400)) {
                $new_image_url = str_replace('../', '', $target_file) . '?v=' . time();
                $stmt_img = $conn->prepare("UPDATE users SET profile_image_url = ? WHERE id = ?");
                $stmt_img->bind_param("si", $new_image_url, $partner_id);
                $stmt_img->execute();
                $message .= '<div class="alert alert-success">Business logo updated successfully.</div>';
            } else { $message .= '<div class="alert alert-danger">Failed to upload image. Please use a valid JPG or PNG.</div>'; }
        }
    }
    // --- Profile Page Request ---
    elseif (isset($_POST['request_profile_page'])) {
        $slug = strtolower(trim($_POST['profile_slug']));
        $slug = preg_replace('/[^a-z0-9-]+/', '', str_replace(' ', '-', $slug));

        $stmt_slug = $conn->prepare("SELECT id FROM users WHERE profile_slug = ? AND id != ?");
        $stmt_slug->bind_param("si", $slug, $partner_id);
        $stmt_slug->execute();
        if ($stmt_slug->get_result()->num_rows > 0) {
            $message .= '<div class="alert alert-danger">That custom URL is already taken. Please choose another.</div>';
        } else {
            $stmt_update = $conn->prepare("UPDATE users SET profile_slug = ?, profile_page_status = 'Requested', is_notified = 0 WHERE id = ?");
            $stmt_update->bind_param("si", $slug, $partner_id);
            $stmt_update->execute();
            $message .= '<div class="alert alert-success">Your request for a profile page has been submitted for admin review.</div>';
        }
    }
    // Re-fetch user data after any updates to show changes immediately
    $user = $conn->query("SELECT * FROM users WHERE id = $partner_id")->fetch_assoc();
}

// --- PRESENTATION BLOCK ---
?>
<div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
    <h1 class="h2">My Profile & Storefront</h1>
</div>
<?php echo $message; ?>
<div class="row">
    <div class="col-lg-8">
        <form method="POST" enctype="multipart/form-data">
            <div class="card shadow-sm mb-4">
                <div class="card-header">Business Details</div>
                <div class="card-body">
                    <div class="mb-3"><label>Business / Display Name</label><input type="text" name="full_name" class="form-control" value="<?php echo htmlspecialchars($user['full_name']); ?>" required></div>
                    <div class="mb-3"><label>Bio (for public storefront page)</label><textarea name="bio" class="form-control" rows="4" placeholder="Tell customers about your business..."><?php echo htmlspecialchars($user['bio'] ?? ''); ?></textarea></div>
                    <div class="mb-3"><label>Contact Phone</label><input type="text" name="phone_number" class="form-control" value="<?php echo htmlspecialchars($user['phone_number'] ?? ''); ?>"></div>
                    <div class="mb-3"><label>Payout Details (e.g., GCash/Bank Info)</label><textarea name="payout_details" class="form-control" rows="4" placeholder="e.g.,&#10;GCash&#10;Juan Dela Cruz&#10;09171234567"><?php echo htmlspecialchars($user['payout_details'] ?? ''); ?></textarea></div>
                    <button type="submit" name="update_details" class="btn btn-primary">Save Details</button>
                </div>
            </div>
        </form>
        <form method="POST">
            <div class="card shadow-sm mb-4">
                <div class="card-header">Change Password</div>
                <div class="card-body">
                    <div class="mb-3"><label>Current Password</label><input type="password" name="current_password" class="form-control" required></div>
                    <div class="mb-3"><label>New Password (min. 8 characters)</label><input type="password" name="new_password" class="form-control"></div>
                    <div class="mb-3"><label>Confirm New Password</label><input type="password" name="confirm_password" class="form-control"></div>
                    <button type="submit" name="change_password" class="btn btn-primary">Change Password</button>
                </div>
            </div>
        </form>
    </div>
    <div class="col-lg-4">
        <form method="POST" enctype="multipart/form-data">
            <div class="card shadow-sm mb-4">
                <div class="card-header">Business Logo</div>
                <div class="card-body text-center">
                    <?php if (!empty($user['profile_image_url'])): ?>
                        <img src="../<?php echo htmlspecialchars($user['profile_image_url']); ?>" class="img-thumbnail rounded-circle mb-3" style="width: 150px; height: 150px; object-fit: cover;">
                    <?php endif; ?>
                    <div class="mb-3"><label class="form-label">Upload New Logo</label><input type="file" name="profile_image" class="form-control" accept="image/jpeg, image/png"></div>
                    <button type="submit" name="upload_logo" class="btn btn-secondary">Upload Logo</button>
                </div>
            </div>
        </form>
        <div class="card shadow-sm">
            <div class="card-header fw-bold">My Public Storefront</div>
            <div class="card-body">
                <?php if ($user['is_verified'] == 0): ?>
                    <div class="alert alert-warning">You must be a <span class="verified-badge"><i class="bi bi-patch-check-fill"></i> Verified Partner</span> before you can request a storefront page.</div>
                <?php elseif ($user['profile_page_status'] == 'Active'): ?>
                    <p>Your storefront page is live!</p><a href="/partner/<?php echo htmlspecialchars($user['profile_slug']); ?>" target="_blank" class="btn btn-success"><i class="bi bi-eye-fill"></i> View My Storefront</a>
                <?php elseif ($user['profile_page_status'] == 'Requested'): ?>
                    <div class="alert alert-info">Your request is pending admin approval. You will be notified once it is reviewed.</div>
                <?php else: // Status is 'None' and partner is verified ?>
                    <p>Request a public page to showcase your listings.</p>
                    <form method="POST">
                        <label class="form-label">Choose Your Custom URL:</label>
                        <div class="input-group mb-2"><span class="input-group-text">.../partner/</span><input type="text" name="profile_slug" class="form-control" required placeholder="e.g., my-tours"></div>
                        <button type="submit" name="request_profile_page" class="btn btn-primary">Submit Request</button>
                    </form>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>
<?php include 'footer.php'; ?>
