<?php
/**
 * Kitchen Staff Sign In API
 * Authenticates kitchen/chef staff using chef table
 */

header('Content-Type: application/json');
require_once 'config.php';

session_start();

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    sendResponse(false, 'Only POST method allowed', null);
}

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

// Validate input
if (!isset($input['password'])) {
    sendResponse(false, 'Password is required', null);
}

if (!isset($input['employee_id']) && !isset($input['email'])) {
    sendResponse(false, 'Employee ID or email is required', null);
}

try {
    // First, ensure the chef table has authentication fields
    $check_columns = $conn->query("DESCRIBE chefs");
    $table_columns = [];
    while ($col = $check_columns->fetch_assoc()) {
        $table_columns[] = $col['Field'];
    }
    
    // Check if password column exists, if not add authentication fields
    if (!in_array('password', $table_columns)) {
        // Add missing columns
        if (!in_array('email', $table_columns)) {
            $conn->query("ALTER TABLE chefs ADD COLUMN email VARCHAR(255) UNIQUE");
        }
        if (!in_array('password', $table_columns)) {
            $conn->query("ALTER TABLE chefs ADD COLUMN password VARCHAR(255)");
        }
        if (!in_array('employee_id', $table_columns)) {
            $conn->query("ALTER TABLE chefs ADD COLUMN employee_id VARCHAR(50) UNIQUE");
        }
        if (!in_array('role', $table_columns)) {
            $conn->query("ALTER TABLE chefs ADD COLUMN role VARCHAR(50) DEFAULT 'Chef'");
        }
        if (!in_array('status', $table_columns)) {
            $conn->query("ALTER TABLE chefs ADD COLUMN status VARCHAR(20) DEFAULT 'active'");
        }
    }
    
    $password = $input['password'];
    $employee_id = isset($input['employee_id']) ? $input['employee_id'] : null;
    $email = isset($input['email']) ? $input['email'] : null;
    $remember_me = isset($input['remember_me']) ? (bool)$input['remember_me'] : false;
    
    // Query for chef by employee_id or email
    if ($employee_id) {
        $sql = "SELECT id, name, email, password, employee_id, position, role, status, image_path 
                FROM chefs 
                WHERE (employee_id = ? OR email = ?) AND status = 'active'
                LIMIT 1";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param('ss', $employee_id, $employee_id);
    } else {
        $sql = "SELECT id, name, email, password, employee_id, position, role, status, image_path 
                FROM chefs 
                WHERE email = ? AND status = 'active'
                LIMIT 1";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param('s', $email);
    }
    
    $stmt->execute();
    $result = $stmt->get_result();
    
    if ($result->num_rows === 0) {
        sendResponse(false, 'Invalid employee ID/email or account is inactive', null);
    }
    
    $chef = $result->fetch_assoc();
    $stmt->close();
    
    // Verify password
    if (!password_verify($password, $chef['password'])) {
        sendResponse(false, 'Invalid password', null);
    }
    
    // Create session
    $_SESSION['kitchen_staff_id'] = $chef['id'];
    $_SESSION['kitchen_staff_name'] = $chef['name'];
    $_SESSION['kitchen_staff_email'] = $chef['email'];
    $_SESSION['kitchen_staff_role'] = $chef['role'];
    $_SESSION['kitchen_staff_position'] = $chef['position'];
    $_SESSION['kitchen_staff_image'] = $chef['image_path'];
    $_SESSION['kitchen_staff_login_time'] = time();
    
    // If remember me is checked, set longer session timeout
    if ($remember_me) {
        $_SESSION['kitchen_staff_remember_me'] = true;
        ini_set('session.cookie_lifetime', 60 * 60 * 24 * 30); // 30 days
    }
    
    sendResponse(true, 'Sign in successful', [
        'chef_id' => $chef['id'],
        'chef_name' => $chef['name'],
        'chef_email' => $chef['email'],
        'chef_role' => $chef['role'],
        'chef_position' => $chef['position'],
        'chef_image' => $chef['image_path']
    ]);
    
} catch (Exception $e) {
    http_response_code(500);
    sendResponse(false, 'Authentication error: ' . $e->getMessage(), null);
}

$conn->close();
?>
