<?php 
require_once 'shikanisha.kts.php'; // Database connection
session_start();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $username = $_POST['username'] ?? '';
    $password = $_POST['password'] ?? '';
    $date = date('Y-m-d H:i:s');

    // Response array
    $response = [
        'success' => false,
        'message' => 'Invalid username or password',
        'redirect' => null
    ];

    // Get user from database
    $stmt = $conn->prepare("SELECT employee_id, username, password, phone_number, type, role_id 
                          FROM employees WHERE username = ?");
    $stmt->bind_param("s", $username);
    $stmt->execute();
    $result = $stmt->get_result();

    // Check if user exists
    if ($result->num_rows === 0) {
        $response['message'] = 'User not found';
        echo json_encode($response);
        exit();
    }

    $user = $result->fetch_assoc();
    
    // Password check (plaintext)
    if ($password === $user['password']) {
        // Get user type (cashier/waiter/etc)
        $userType = strtolower($user['type']);
        
        // Check for active shift (only for waiters and cashiers)
    // Check for active shift (only for waiters and cashiers)
if (in_array($userType, ['waiter', 'cashier'])) {
    $shiftCheck = $conn->prepare("SELECT `shift_id`, `employee_id`, `start_time`, `end_time`, `starting_cash`, `ending_cash`, `status`, `notes` 
                                FROM `shifts` 
                                WHERE `status` = 'active' AND `employee_id` = ?");
    $shiftCheck->bind_param("i", $user['employee_id']);
    $shiftCheck->execute();
    $shiftResult = $shiftCheck->get_result();
    $activeShiftExists = $shiftResult->num_rows > 0;
    
    if (!$activeShiftExists) {
        if ($userType === 'waiter') {
            // Waiters can't work without an active shift
            $response = [
                'success' => false,
                'message' => 'No active shift available. Please wait for a cashier to start a shift.',
                'redirect' => 'login.php'
            ];
            echo json_encode($response);
            exit();
        } else if ($userType === 'cashier') {
            // Cashiers should be redirected to start shift page
            // Set session variables only for cashiers who need to start shift
            $_SESSION['eid'] = $user['employee_id'];
            $_SESSION['user_id'] = $user['employee_id'];
            $_SESSION['type'] = $user['type'];
            $_SESSION['role_id'] = $user['role_id'];
            $_SESSION['user'] = $user['username'];
            $_SESSION['phone'] = $user['phone_number'];

            $logStmt = $conn->prepare("INSERT INTO logs (logintime, username, user_id) VALUES (?, ?, ?)");
            $logStmt->bind_param("ssi", $date, $user['username'], $user['employee_id']);
            $logStmt->execute();

            $response = [
                'success' => true,
                'message' => 'Please start a new shift',
                'redirect' => 'shift.php',
                'data' => [
                    'username' => $user['username'],
                    'phone' => $user['phone_number'],
                    'type' => $user['type'],
                    'role_id' => $user['role_id']
                ]
            ];
            echo json_encode($response);
            exit();
        }
    }
}
        // Set session variables for successful login (after shift check)
        $_SESSION['eid'] = $user['employee_id'];
        $_SESSION['user_id'] = $user['employee_id'];
        $_SESSION['type'] = $user['type'];
        $_SESSION['role_id'] = $user['role_id'];
        $_SESSION['user'] = $user['username'];
        $_SESSION['phone'] = $user['phone_number'];

        // Log login
        $logStmt = $conn->prepare("INSERT INTO logs (logintime, username, user_id) VALUES (?, ?, ?)");
        $logStmt->bind_param("ssi", $date, $user['username'], $user['employee_id']);
        $logStmt->execute();

        // Default success case (active shift exists or user doesn't need shift)
        $response = [
            'success' => true,
            'message' => 'Login successful',
            'data' => [
                'username' => $user['username'],
                'phone' => $user['phone_number'],
                'type' => $user['type'],
                'role_id' => $user['role_id']
            ],
            'redirect' => 'index.php'
        ];
    }

    // Send response
    header('Content-Type: application/json');
    echo json_encode($response);
    exit();
}
?>