<?php
$host = "localhost";
$username = "kmir2197_panColor";
$password = "ColorPanel33#";
$database = "kmir2197_panColor";

// Create connection
$conn = new mysqli($host, $username, $password, $database);

// Check connection
if ($conn->connect_error) {
    error_log("Database connection failed: " . $conn->connect_error);
    die("Connection failed: " . $conn->connect_error);
}

// Set character set
$conn->set_charset("utf8mb4");

// Function to sanitize user input
function sanitize_input($conn, $data) {
    if (is_array($data)) {
        $sanitized = [];
        foreach ($data as $key => $value) {
            $sanitized[$key] = sanitize_input($conn, $value);
        }
        return $sanitized;
    }
    return $conn->real_escape_string(trim($data));
}

// Function to verify password - handles both hashed and plain text passwords
function verify_password($input_password, $stored_password) {
    // Check if it's empty
    if (empty($input_password) || empty($stored_password)) {
        return false;
    }
    
    // Try PHP's password verification (if password is hashed)
    if (password_verify($input_password, $stored_password)) {
        return true;
    }
    
    // If all else fails, compare directly (not recommended for production)
    return ($input_password === $stored_password);
}

// Function to hash a password securely
function hash_password($password) {
    return password_hash($password, PASSWORD_BCRYPT, ['cost' => 12]);
}

// Function to check if user is logged in
function is_logged_in() {
    return isset($_SESSION['logged_in']) && $_SESSION['logged_in'] === true;
}

// Function to check user type (admin, it, borrower, or colorroom)
function is_user_type($type) {
    return isset($_SESSION['user_type']) && $_SESSION['user_type'] === $type;
}

// Function to redirect to login page if not logged in
function redirect_if_not_logged_in() {
    if (!is_logged_in()) {
        header("Location: ../login.php");
        exit();
    }
}

// Function to redirect to login page if not admin
function redirect_if_not_admin() {
    if (!is_logged_in() || !is_user_type('admin')) {
        header("Location: ../login.php");
        exit();
    }
}

// Function to redirect to login page if not borrower
function redirect_if_not_borrower() {
    if (!is_logged_in() || !is_user_type('borrower')) {
        header("Location: ../login.php");
        exit();
    }
}

// Function to redirect to login page if not IT user
function redirect_if_not_it() {
    if (!is_logged_in() || !is_user_type('it')) {
        header("Location: ../login.php");
        exit();
    }
}

// Function to redirect to login page if not color room user
function redirect_if_not_colorroom() {
    if (!is_logged_in() || !is_user_type('colorroom')) {
        header("Location: ../login.php");
        exit();
    }
}

// Function to check if user account is active
function is_account_active($conn, $user_id, $user_type) {
    $status = null;
    
    switch ($user_type) {
        case 'admin':
            $stmt = $conn->prepare("SELECT status FROM admin_users WHERE id = ?");
            break;
        case 'borrower':
            $stmt = $conn->prepare("SELECT status FROM borrower_users WHERE id = ?");
            break;
        case 'colorroom':
            $stmt = $conn->prepare("SELECT status FROM color_room_users WHERE id = ?");
            break;
        case 'it':
            // IT accounts don't have status field (they're always active)
            return true;
        default:
            return false;
    }
    
    if ($stmt) {
        $stmt->bind_param("i", $user_id);
        $stmt->execute();
        $result = $stmt->get_result();
        
        if ($row = $result->fetch_assoc()) {
            $status = $row['status'];
        }
        
        $stmt->close();
    }
    
    return $status === 'active';
}

// Function to verify active status and redirect if inactive
function verify_active_status($conn) {
    if (!is_logged_in()) {
        return false;
    }
    
    // IT users are always active
    if (is_user_type('it')) {
        return true;
    }
    
    $user_id = $_SESSION['user_id'];
    $user_type = $_SESSION['user_type'];
    
    if (!is_account_active($conn, $user_id, $user_type)) {
        // Log this attempt
        error_log("Nonactive {$user_type} account attempted access: {$_SESSION['username']} (ID: {$user_id})");
        
        // Clear all session variables
        $_SESSION = array();
        
        // Destroy the session
        session_destroy();
        
        // Redirect to login with message
        header("Location: ../login.php?error=inactive");
        exit();
    }
    
    return true;
}

// Function to log activity - now using audit_logs
function log_activity($conn, $user_id, $user_type, $action, $details = '') {
    return create_audit_log($conn, $action, $user_id, $user_type, $details);
}

// Function to generate CSRF token
function generate_csrf_token() {
    if (!isset($_SESSION['csrf_token'])) {
        $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
    }
    
    return $_SESSION['csrf_token'];
}

// Function to verify CSRF token
function verify_csrf_token($token) {
    if (!isset($_SESSION['csrf_token'])) {
        return false;
    }
    
    return hash_equals($_SESSION['csrf_token'], $token);
}

// Function to create audit log for important actions
function create_audit_log($conn, $action_type, $user_id, $user_type, $details) {
    $stmt = $conn->prepare("INSERT INTO audit_logs (action_type, user_id, user_type, details, timestamp, ip_address) 
                          VALUES (?, ?, ?, ?, NOW(), ?)");
    
    if ($stmt) {
        $ip = $_SERVER['REMOTE_ADDR'] ?? 'Unknown';
        
        $stmt->bind_param("sisss", $action_type, $user_id, $user_type, $details, $ip);
        $stmt->execute();
        $stmt->close();
        
        return true;
    }
    
    return false;
}

// Create the audit_logs table if it doesn't exist (for security audit)
$conn->query("CREATE TABLE IF NOT EXISTS audit_logs (
    id INT AUTO_INCREMENT PRIMARY KEY,
    action_type VARCHAR(50) NOT NULL,
    user_id INT,
    user_type VARCHAR(20) CHECK (user_type IN ('admin', 'it', 'borrower', 'colorroom')),
    details TEXT,
    timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
    ip_address VARCHAR(45)
)");
?>