<?php

header('Content-Type: application/json');


if (session_status() == PHP_SESSION_NONE) {
    session_start();
}


require_once '../../classes/Database.php';
require_once '../../includes/auth.php';

$database = new Database();
$conn = $database->getConnection();
$auth = new Auth($conn);


if (!$auth->isSuperAdmin($_SESSION['user_id']) &&
    !$auth->isWarehousePersonnel($_SESSION['user_id']) &&
    !$auth->isBranchManager($_SESSION['user_id'])) {
    http_response_code(403);
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}


$sessionId = isset($_POST['session_id']) ? (int)$_POST['session_id'] : 0;
$userRole = $_POST['user_role'] ?? '';

if (!$sessionId || !in_array($userRole, ['admin', 'branch_manager'])) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Invalid request data']);
    exit;
}

try {

    require_once '../../classes/StockTaking.php';
    $stockTaking = new StockTaking($conn);


    if (!$stockTaking->canUserPerformAction($sessionId, $_SESSION['user_id'], $userRole, 'start')) {
        echo json_encode(['success' => false, 'message' => 'You cannot start this session']);
        exit;
    }


    $sessionSql = "SELECT branch_id FROM stock_taking_sessions WHERE session_id = :session_id";
    $sessionStmt = $conn->prepare($sessionSql);
    $sessionStmt->bindValue(':session_id', $sessionId, PDO::PARAM_INT);
    $sessionStmt->execute();
    $sessionData = $sessionStmt->fetch(PDO::FETCH_ASSOC);

    if (!$sessionData) {
        echo json_encode(['success' => false, 'message' => 'Session not found']);
        exit;
    }


    $result = $stockTaking->startSessionDual(
        $sessionData['branch_id'],
        $_SESSION['user_id'],
        $userRole,
        ''
    );

    if ($result) {
        echo json_encode([
            'success' => true,
            'message' => 'Session started successfully',
            'session_id' => $result
        ]);
    } else {
        http_response_code(500);
        echo json_encode(['success' => false, 'message' => 'Failed to start session']);
    }
} catch (Exception $e) {
    error_log("Error in start_session_dual.php: " . $e->getMessage());
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Server error: ' . $e->getMessage()]);
}
?>