<?php
// File: follow_handler.php
session_start();
require_once 'db.php';

// --- SECURITY CHECK: User must be logged in to follow ---
if (!isset($_SESSION['user_id'])) {
    // If the user is not logged in, redirect them to the login page.
    // We pass a 'redirect_url' so they can be sent back to the profiles page after logging in.
    $_SESSION['login_redirect_url'] = 'profiles.php';
    header('Location: login.php?error=login_required');
    exit();
}

// Check if the form was submitted
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['artist_id'])) {
    
    $customer_id = $_SESSION['user_id'];
    $artist_id = filter_var($_POST['artist_id'], FILTER_SANITIZE_NUMBER_INT);

    // --- HANDLE FOLLOW ACTION ---
    if (isset($_POST['follow'])) {
        // Prevent a user from following themselves
        if ($customer_id != $artist_id) {
            $stmt = $conn->prepare("INSERT INTO followers (customer_id, artist_id) VALUES (?, ?)");
            $stmt->bind_param("ii", $customer_id, $artist_id);
            $stmt->execute();
        }
    } 
    // --- HANDLE UNFOLLOW ACTION ---
    elseif (isset($_POST['unfollow'])) {
        $stmt = $conn->prepare("DELETE FROM followers WHERE customer_id = ? AND artist_id = ?");
        $stmt->bind_param("ii", $customer_id, $artist_id);
        $stmt->execute();
    }

    // Redirect back to the profiles page
    header('Location: profiles.php');
    exit();

} else {
    // If the script is accessed directly or without the necessary data, redirect home.
    header('Location: index.php');
    exit();
}
?>
