<?php
/**
 * Store Keeper Login API
 * Handles authentication for store keeper users
 */

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

require_once 'config.php';

$action = isset($_GET['action']) ? $_GET['action'] : 'login';
$method = $_SERVER['REQUEST_METHOD'];

try {
    // Create table if not exists
    createStoreKeepersTable();

    switch ($action) {
        case 'login':
            if ($method !== 'POST') {
                throw new Exception('Invalid request method');
            }
            handleLogin();
            break;

        case 'logout':
            handleLogout();
            break;

        case 'check_session':
            checkSession();
            break;

        default:
            sendResponse(false, 'Invalid action', null);
    }

} catch (Exception $e) {
    http_response_code(400);
    sendResponse(false, $e->getMessage(), null);
}

/**
 * Create store_keepers table if it doesn't exist
 */
function createStoreKeepersTable() {
    global $conn;

    $sql = "CREATE TABLE IF NOT EXISTS store_keepers (
        id INT PRIMARY KEY AUTO_INCREMENT,
        name VARCHAR(100) NOT NULL,
        email VARCHAR(100) UNIQUE NOT NULL,
        password VARCHAR(255) NOT NULL,
        phone VARCHAR(20),
        status ENUM('active', 'inactive') DEFAULT 'active',
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        last_login TIMESTAMP NULL,
        INDEX idx_email (email),
        INDEX idx_status (status)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4";

    if (!$conn->query($sql)) {
        throw new Exception('Error creating table: ' . $conn->error);
    }
}

/**
 * Handle login
 */
function handleLogin() {
    global $conn;

    $input = json_decode(file_get_contents('php://input'), true);

    if (!isset($input['email']) || !isset($input['password'])) {
        sendResponse(false, 'Email and password are required', null);
    }

    $email = htmlspecialchars($input['email']);
    $password = $input['password'];

    // Check if store keeper exists
    $sql = "SELECT * FROM store_keepers WHERE email = ? AND status = 'active'";
    $stmt = $conn->prepare($sql);

    if (!$stmt) {
        throw new Exception('Database error: ' . $conn->error);
    }

    $stmt->bind_param('s', $email);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows === 0) {
        sendResponse(false, 'Invalid email or password', null);
    }

    $store_keeper = $result->fetch_assoc();
    $stmt->close();

    // Verify password
    if (!password_verify($password, $store_keeper['password'])) {
        sendResponse(false, 'Invalid email or password', null);
    }

    // Update last login
    $updateSql = "UPDATE store_keepers SET last_login = NOW() WHERE id = ?";
    $updateStmt = $conn->prepare($updateSql);
    $updateStmt->bind_param('i', $store_keeper['id']);
    $updateStmt->execute();
    $updateStmt->close();

    // Set session variables
    $_SESSION['store_keeper_id'] = $store_keeper['id'];
    $_SESSION['store_keeper_name'] = $store_keeper['name'];
    $_SESSION['store_keeper_email'] = $store_keeper['email'];
    $_SESSION['store_keeper_phone'] = $store_keeper['phone'];
    $_SESSION['last_activity'] = time();

    sendResponse(true, 'Login successful', [
        'id' => $store_keeper['id'],
        'name' => $store_keeper['name'],
        'email' => $store_keeper['email']
    ]);
}

/**
 * Handle logout
 */
function handleLogout() {
    session_destroy();
    sendResponse(true, 'Logged out successfully', null);
}

/**
 * Check if session is valid
 */
function checkSession() {
    if (isset($_SESSION['store_keeper_id']) && !empty($_SESSION['store_keeper_id'])) {
        sendResponse(true, 'Session is valid', [
            'id' => $_SESSION['store_keeper_id'],
            'name' => $_SESSION['store_keeper_name'],
            'email' => $_SESSION['store_keeper_email']
        ]);
    } else {
        sendResponse(false, 'No active session', null);
    }
}

?>
