<?php
session_start();
// Since we are inside the 'system' folder, we just include conn.php directly
require_once 'conn.php';

if (isset($_GET['id']) && isset($_SESSION['username'])) {
    
    $target_branch_id = $_GET['id'];
    $current_username = $_SESSION['username'];

    // SECURITY: Only allow switching if the target branch belongs to the SAME username
    $stmt = $conn->prepare("SELECT id FROM branch WHERE id = ? AND username = ? AND status = 1");
    $stmt->execute([$target_branch_id, $current_username]);
    $branch_data = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($branch_data) {
        // Update Session to new branch
        $_SESSION['branch'] = $branch_data['id'];
        $_SESSION['user_id'] = $branch_data['id']; 
        
        // Go back to the dashboard (one level up from 'system/')
        header("Location: ../home.php");
        exit;
    } else {
        echo "<script>alert('Access Denied.'); window.location.href='../home.php';</script>";
        exit;
    }
} else {
    header("Location: ../home.php");
    exit;
}
?>