<?php
session_start();
include 'config.php';   // connects to xtodo_main_leads

if (isset($_POST['login'])) {

    $username  = $_POST['username'];
    $password  = $_POST['password'];
    $branch_id = $_POST['branch_id'];

    // 1️⃣ get selected branch details
    $branch_sql = "SELECT * FROM branches WHERE id = ?";
    $branch_stmt = $conn->prepare($branch_sql);
    $branch_stmt->bind_param("i", $branch_id);
    $branch_stmt->execute();
    $branch_result = $branch_stmt->get_result();

    if ($branch_result->num_rows === 0) {
        echo "<script>alert('Invalid branch'); window.location='index.php';</script>";
        exit;
    }

    $branch = $branch_result->fetch_assoc();
    $branch_db = $branch['branch_db']; // branch DB name

    // 2️⃣ CONNECT TO BRANCH DATABASE
    $db = new mysqli("localhost", "xtodo_systemsoft", ";)u&S9wx6#xD87l^", $branch_db);

    if ($db->connect_error) {
        echo "<script>alert('Cannot connect to branch database'); window.location='index.php';</script>";
        exit;
    }

    // 3️⃣ Validate user inside branch DB
    $sql = "SELECT * FROM users WHERE username = ? AND status = 1";
    $stmt = $db->prepare($sql);
    $stmt->bind_param("s", $username);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows == 1) {
        $user = $result->fetch_assoc();

        if (password_verify($password, $user['password'])) {

            // 4️⃣ Save session data
            $_SESSION['userid']      = $user['id'];
            $_SESSION['username']    = $user['username'];
            $_SESSION['user_name']    = $user['username'];
            $_SESSION['branch_id']   = $branch['id'];
            $_SESSION['branch_name'] = $branch['branch_name'];
            $_SESSION['branch_code'] = $branch['branchcode'];

            // Store branch database name
            $_SESSION['branch_db']   = $branch_db;

            header("Location: dashboard.php");
            exit;
        } else {
            echo "<script>alert('Invalid password'); window.location='index.php';</script>";
        }

    } else {
        echo "<script>alert('Invalid username'); window.location='index.php';</script>";
    }
}
?>
