<?php
require_once __DIR__ . '/../connection.php';

class AdminController {
    private $conn;

    public function __construct($db) {
        $this->conn = $db;
        session_start();
    }

    // Admin login
    public function login($username, $password = null, $isPhoneLogin = false, $adminData = null) {
        try {
            // If this is a phone-based login and we have admin data, use it directly
            if ($isPhoneLogin && $adminData) {
                $admin = $adminData;
            } else {
                // For regular username/password login
                $query = "SELECT * FROM staff WHERE user_name = ? AND user_type = 'admin' LIMIT 1";
                $stmt = $this->conn->prepare($query);
                $stmt->bind_param("s", $username);
                $stmt->execute();
                $result = $stmt->get_result();
                
                if ($result->num_rows === 0) {
                    return ['status' => 'error', 'message' => 'Invalid credentials'];
                }
                
                $admin = $result->fetch_assoc();
                
                // Verify password for non-phone login
                if (!$isPhoneLogin && $password !== $admin['password']) {
                    return ['status' => 'error', 'message' => 'Invalid credentials'];
                }
            }
            
            // Regenerate session ID to prevent session fixation
            session_regenerate_id(true);
            
            // Set session variables
            $_SESSION['admin_logged_in'] = true;
            $_SESSION['admin_id'] = $admin['uid'];
            $_SESSION['admin_name'] = $admin['name'];
            $_SESSION['company_id'] = $admin['com_id'] ?? null;
            $_SESSION['last_activity'] = time();
            
            // Generate auth token
            $auth_token = bin2hex(random_bytes(32));
            $expires = date('Y-m-d H:i:s', strtotime('+8 hours'));
            
            // Store token in database
            $query = "UPDATE staff SET auth_token = ?, token_expires = ? WHERE uid = ?";
            $stmt = $this->conn->prepare($query);
            $stmt->bind_param("ssi", $auth_token, $expires, $admin['uid']);
            
            if (!$stmt->execute()) {
                throw new Exception("Failed to update auth token");
            }
            
            return [
                'status' => 'success',
                'message' => 'Login successful',
                'auth_token' => $auth_token,
                'admin' => [
                    'id' => $admin['uid'],
                    'name' => $admin['name'],
                    'username' => $admin['user_name'],
                    'company_id' => $admin['com_id'] ?? null
                ]
            ];
        } catch (Exception $e) {
            error_log("Admin Login Error: " . $e->getMessage());
            return ['status' => 'error', 'message' => 'An error occurred during login'];
        }
    }
    
    // Check if admin is logged in
    public function isLoggedIn($auth_token = null) {
        try {
            if (empty($auth_token) && !empty($_SESSION['admin_logged_in'])) {
                return true;
            }
            
            if (!empty($auth_token)) {
                $query = "SELECT * FROM staff WHERE auth_token = ? AND token_expires > NOW() AND user_type = 'admin' LIMIT 1";
                $stmt = $this->conn->prepare($query);
                $stmt->bind_param("s", $auth_token);
                $stmt->execute();
                $result = $stmt->get_result();
                
                if ($result->num_rows > 0) {
                    $admin = $result->fetch_assoc();
                    $_SESSION['admin_logged_in'] = true;
                    $_SESSION['admin_id'] = $admin['uid'];
                    $_SESSION['admin_name'] = $admin['name'];
                    return true;
                }
            }
            
            return false;
            
        } catch (Exception $e) {
            error_log("Admin Auth Check Error: " . $e->getMessage());
            return false;
        }
    }
    
    // Logout admin
    public function logout() {
        try {
            if (isset($_SESSION['admin_id'])) {
                $query = "UPDATE staff SET auth_token = NULL, token_expires = NULL WHERE uid = ?";
                $stmt = $this->conn->prepare($query);
                $stmt->bind_param("i", $_SESSION['admin_id']);
                $stmt->execute();
            }
            
            session_unset();
            session_destroy();
            
            return ['status' => 'success', 'message' => 'Logged out successfully'];
            
        } catch (Exception $e) {
            error_log("Admin Logout Error: " . $e->getMessage());
            return ['status' => 'error', 'message' => 'Failed to logout'];
        }
    }
}
