<?php
include 'header.php'; // Includes partner session check, DB connection, and partner data
require_once '../includes/image-resizer.php'; // We'll use our image resizer for logos

$message = '';
// Handle form submission
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $full_name = trim($_POST['full_name']);
    $phone_number = trim($_POST['phone_number']);

    // Update basic details
    $stmt_update = $conn->prepare("UPDATE users SET full_name = ?, phone_number = ? WHERE id = ?");
    $stmt_update->bind_param("ssi", $full_name, $phone_number, $partner_id);
    $stmt_update->execute();
    $message .= '<div class="alert alert-success">Profile details updated successfully.</div>';

    // Handle password change
    if (!empty($_POST['new_password'])) {
        if (strlen($_POST['new_password']) < 8) {
            $message .= '<div class="alert alert-danger">Password must be at least 8 characters long.</div>';
        } elseif ($_POST['new_password'] !== $_POST['confirm_password']) {
            $message .= '<div class="alert alert-danger">New passwords do not match.</div>';
        } else {
            $hashed_password = password_hash($_POST['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>';
        }
    }

    // Handle business logo upload
    if (isset($_FILES['profile_image']) && $_FILES['profile_image']['error'] == 0) {
        $target_dir = "../uploads/logos/";
        $image_extension = strtolower(pathinfo($_FILES["profile_image"]["name"], PATHINFO_EXTENSION));
        $target_file = $target_dir . "partner-logo-" . $partner_id . "." . $image_extension;
        
        // Resize to a 400x400 square, good for logos
        if (resizeImage($_FILES["profile_image"]["tmp_name"], $target_file, 400, 400)) {
            $new_image_url = str_replace('../', '', $target_file) . '?v=' . time(); // Add version to break cache
            $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 or resize image. Please use a valid JPG or PNG.</div>';
        }
    }
    
    // Refresh user data after updates to show changes immediately
    $stmt_refresh = $conn->prepare("SELECT * FROM users WHERE id = ?");
    $stmt_refresh->bind_param("i", $partner_id);
    $stmt_refresh->execute();
    $user = $stmt_refresh->get_result()->fetch_assoc();
    $_SESSION['user_name'] = $user['full_name']; // Re-sync session name
}
?>

<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">Edit Profile & Business Info</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 class="form-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 class="form-label">Contact Email</label><input type="email" class="form-control" value="<?php echo htmlspecialchars($user['email']); ?>" disabled><small class="text-muted">Email cannot be changed.</small></div>
                    <div class="mb-3"><label class="form-label">Contact Phone</label><input type="text" name="phone_number" class="form-control" value="<?php echo htmlspecialchars($user['phone_number']); ?>"></div>
                </div>
            </div>

            <div class="card shadow-sm mb-4">
                <div class="card-header">Change Password</div>
                <div class="card-body">
                    <div class="mb-3"><label class="form-label">New Password</label><input type="password" name="new_password" class="form-control" placeholder="Leave blank to keep current password"></div>
                    <div class="mb-3"><label class="form-label">Confirm New Password</label><input type="password" name="confirm_password" class="form-control"></div>
                </div>
            </div>

             <div class="card shadow-sm mb-4">
                <div class="card-header">Business Logo</div>
                <div class="card-body">
                     <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">
                        <?php if (!empty($user['profile_image_url'])): ?>
                            <div class="mt-2"><small>Current Logo:</small><br><img src="../<?php echo htmlspecialchars($user['profile_image_url']); ?>" class="img-thumbnail" style="max-width: 200px;"></div>
                        <?php endif; ?>
                     </div>
                </div>
            </div>

            <button type="submit" class="btn btn-primary btn-lg">Save Changes</button>
        </form>
    </div>
</div>

<?php include 'footer.php'; ?>
