<?php 
require_once 'shikanisha.kts.php';

// Start the session
session_start();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $username = $_POST['username'];
    $password = $_POST['password'];
    $role = $_POST['rank'];
    $date = date('Y-m-d H:i:s'); // Use a standardized format for the timestamp

    // Prepare the SQL statement
    $stmt = $conn->prepare("SELECT * FROM employees WHERE username = ? AND password = ? AND type = ?");
    $stmt->bind_param("sss", $username, $password, $role);
    $stmt->execute();

    // Get the result
    $result = $stmt->get_result();

    // Check if the credentials are valid
    if ($result->num_rows === 0) {
        // Handle invalid credentials securely
        // You can set an error message and respond to the client
        echo 'error';
        exit();
    }

    // Get the user's details
    $row = $result->fetch_assoc();
    $phone = $row['phone_number'];
    $_SESSION['type'] = $row['type'];
    $_SESSION['eid'] = $row['employee_id'];
    $uid = $_SESSION['eid'];

    // Insert login time and username into logs table
    $stmt = $conn->prepare("INSERT INTO logs (logintime, username) VALUES (?, ?)");
    $stmt->bind_param("ss", $date, $username);
    $stmt->execute();

    // Store the user's details in the session
    $_SESSION['user'] = $username;
    $_SESSION['phone'] = $phone;

    // Respond to the client with 'success'
    echo 'success';
}
?>
