<?php
include_once __DIR__ . '/../config/database.php';

class AdminController {
    private $db;

    public function __construct() {
        $database = new Database();
        $this->db = $database->getConnection();
    }

    private function verifyAdmin() {
        $headers = apache_request_headers();
        $token = isset($headers['Authorization']) ? $headers['Authorization'] : null;
        if (!$token) return null;
        
        $token = str_replace('Bearer ', '', $token);
        $decoded = json_decode(base64_decode($token), true);
        
        if ($decoded && isset($decoded['role']) && $decoded['role'] === 'admin') {
            return $decoded['id'];
        }
        return null;
    }

    private function logAction($adminId, $action) {
        $stmt = $this->db->prepare("INSERT INTO admin_logs (user_id, action) VALUES (?, ?)");
        $stmt->execute([$adminId, $action]);
    }

    public function getStats() {
        if (!$this->verifyAdmin()) {
            http_response_code(403);
            echo json_encode(["message" => "Forbidden."]);
            return;
        }

        $totalUsers = $this->db->query("SELECT COUNT(*) FROM users WHERE role='user'")->fetchColumn();
        $totalBalance = $this->db->query("SELECT COALESCE(SUM(balance),0) FROM accounts")->fetchColumn();
        $totalTransactions = $this->db->query("SELECT COUNT(*) FROM transactions")->fetchColumn();
        $totalCards = $this->db->query("SELECT COUNT(*) FROM cards")->fetchColumn();
        $totalLoans = $this->db->query("SELECT COUNT(*) FROM loans WHERE status='active'")->fetchColumn();
        $totalLoanAmount = $this->db->query("SELECT COALESCE(SUM(amount),0) FROM loans WHERE status='active'")->fetchColumn();
        $totalDeposits = $this->db->query("SELECT COALESCE(SUM(amount),0) FROM deposits WHERE status='completed'")->fetchColumn();

        $recentUsers = $this->db->query("SELECT username, full_name, created_at FROM users ORDER BY created_at DESC LIMIT 5")->fetchAll(PDO::FETCH_ASSOC);
        $recentTx = $this->db->query("SELECT t.transaction_id, t.amount, t.type, t.status, t.created_at, u1.username as sender, u2.username as receiver FROM transactions t LEFT JOIN users u1 ON t.sender_id=u1.id LEFT JOIN users u2 ON t.receiver_id=u2.id ORDER BY t.created_at DESC LIMIT 5")->fetchAll(PDO::FETCH_ASSOC);

        http_response_code(200);
        echo json_encode([
            "total_users" => intval($totalUsers),
            "total_balance" => floatval($totalBalance),
            "total_transactions" => intval($totalTransactions),
            "total_cards" => intval($totalCards),
            "active_loans" => intval($totalLoans),
            "total_loan_amount" => floatval($totalLoanAmount),
            "total_deposits" => floatval($totalDeposits),
            "recent_users" => $recentUsers,
            "recent_transactions" => $recentTx
        ]);
    }

    public function getAllUsers() {
        if (!$this->verifyAdmin()) {
            http_response_code(403);
            echo json_encode(["message" => "Forbidden."]);
            return;
        }

        $stmt = $this->db->prepare("SELECT u.id, u.username, u.email, u.full_name, u.role, u.created_at, COALESCE(a.balance,0) as balance, a.status as account_status, a.id as account_id FROM users u LEFT JOIN accounts a ON u.id=a.user_id ORDER BY u.created_at DESC");
        $stmt->execute();
        $users = $stmt->fetchAll(PDO::FETCH_ASSOC);

        http_response_code(200);
        echo json_encode($users);
    }

    public function updateUser($data) {
        $adminId = $this->verifyAdmin();
        if (!$adminId) {
            http_response_code(403);
            echo json_encode(["message" => "Forbidden."]);
            return;
        }

        if (empty($data->id)) {
            http_response_code(400);
            echo json_encode(["message" => "User ID required."]);
            return;
        }

        $fields = [];
        $params = [];

        if (isset($data->full_name)) {
            $fields[] = "full_name = ?";
            $params[] = $data->full_name;
        }
        if (isset($data->email)) {
            $fields[] = "email = ?";
            $params[] = $data->email;
        }
        if (isset($data->role)) {
            $fields[] = "role = ?";
            $params[] = $data->role;
        }

        if (empty($fields)) {
            http_response_code(400);
            echo json_encode(["message" => "Nothing to update."]);
            return;
        }

        $params[] = $data->id;
        $stmt = $this->db->prepare("UPDATE users SET " . implode(', ', $fields) . " WHERE id = ?");
        $stmt->execute($params);

        $this->logAction($adminId, "Updated user ID: {$data->id}");

        http_response_code(200);
        echo json_encode(["message" => "User updated successfully."]);
    }

    public function deleteUser($data) {
        $adminId = $this->verifyAdmin();
        if (!$adminId) {
            http_response_code(403);
            echo json_encode(["message" => "Forbidden."]);
            return;
        }

        if (empty($data->id)) {
            http_response_code(400);
            echo json_encode(["message" => "User ID required."]);
            return;
        }

        if ($data->id == $adminId) {
            http_response_code(400);
            echo json_encode(["message" => "Cannot delete yourself."]);
            return;
        }

        $stmt = $this->db->prepare("DELETE FROM users WHERE id = ?");
        $stmt->execute([$data->id]);
        $this->logAction($adminId, "Deleted user ID: {$data->id}");

        http_response_code(200);
        echo json_encode(["message" => "User deleted."]);
    }

    public function getAllAccounts() {
        if (!$this->verifyAdmin()) {
            http_response_code(403);
            echo json_encode(["message" => "Forbidden."]);
            return;
        }

        $stmt = $this->db->prepare("SELECT a.id, a.account_number, a.balance, a.currency, a.status, a.created_at, u.username as owner_username, u.full_name as owner_name FROM accounts a JOIN users u ON a.user_id = u.id ORDER BY a.created_at DESC");
        $stmt->execute();
        $accounts = $stmt->fetchAll(PDO::FETCH_ASSOC);

        http_response_code(200);
        echo json_encode($accounts);
    }

    public function createAccount($data) {
        $adminId = $this->verifyAdmin();
        if (!$adminId) {
            http_response_code(403);
            echo json_encode(["message" => "Forbidden."]);
            return;
        }

        if (empty($data->user_id)) {
            http_response_code(400);
            echo json_encode(["message" => "User ID is required."]);
            return;
        }

        $balance = isset($data->balance) ? floatval($data->balance) : 0.00;
        $currency = isset($data->currency) ? $data->currency : 'USD';
        $accNumber = rand(1000000000, 9999999999);

        try {
            $stmt = $this->db->prepare("INSERT INTO accounts (user_id, account_number, balance, currency, status) VALUES (?, ?, ?, ?, 'active')");
            $stmt->execute([$data->user_id, $accNumber, $balance, $currency]);
            $this->logAction($adminId, "Created account $accNumber for user ID $data->user_id");

            http_response_code(201);
            echo json_encode(["message" => "Account created successfully!"]);
        } catch (Exception $e) {
            http_response_code(500);
            echo json_encode(["message" => "Error creating account: " . $e->getMessage()]);
        }
    }

    public function blockAccount($data) {
        $adminId = $this->verifyAdmin();
        if (!$adminId) {
            http_response_code(403);
            echo json_encode(["message" => "Forbidden."]);
            return;
        }

        if (empty($data->account_id)) {
            http_response_code(400);
            echo json_encode(["message" => "Account ID required."]);
            return;
        }

        $status = isset($data->status) ? $data->status : 'frozen';

        try {
            $stmt = $this->db->prepare("UPDATE accounts SET status = ? WHERE id = ?");
            $stmt->execute([$status, $data->account_id]);
            $this->logAction($adminId, "Changed account ID {$data->account_id} status to $status");

            http_response_code(200);
            echo json_encode(["message" => "Account status updated."]);
        } catch (Exception $e) {
            http_response_code(500);
            echo json_encode(["message" => "Error: " . $e->getMessage()]);
        }
    }

    public function adjustBalance($data) {
        $adminId = $this->verifyAdmin();
        if (!$adminId) {
            http_response_code(403);
            echo json_encode(["message" => "Forbidden."]);
            return;
        }

        if (empty($data->user_id) || !isset($data->amount)) {
            http_response_code(400);
            echo json_encode(["message" => "user_id and amount required."]);
            return;
        }

        try {
            $stmt = $this->db->prepare("UPDATE accounts SET balance = balance + ? WHERE user_id = ?");
            $stmt->execute([floatval($data->amount), $data->user_id]);
            $this->logAction($adminId, "Adjusted balance by {$data->amount} for user ID {$data->user_id}");

            http_response_code(200);
            echo json_encode(["message" => "Balance adjusted."]);
        } catch (Exception $e) {
            http_response_code(500);
            echo json_encode(["message" => "Error: " . $e->getMessage()]);
        }
    }

    public function getAllTransactions() {
        if (!$this->verifyAdmin()) {
            http_response_code(403);
            echo json_encode(["message" => "Forbidden."]);
            return;
        }

        $query = "SELECT t.transaction_id, t.amount, t.type, t.status, t.created_at,
                   u1.username as sender_username, u2.username as receiver_username
            FROM transactions t
            LEFT JOIN users u1 ON t.sender_id = u1.id
            LEFT JOIN users u2 ON t.receiver_id = u2.id
            ORDER BY t.created_at DESC";
        $stmt = $this->db->prepare($query);
        $stmt->execute();
        $transactions = $stmt->fetchAll(PDO::FETCH_ASSOC);

        http_response_code(200);
        echo json_encode($transactions);
    }

    public function getAllCards() {
        if (!$this->verifyAdmin()) {
            http_response_code(403);
            echo json_encode(["message" => "Forbidden."]);
            return;
        }

        $stmt = $this->db->prepare("SELECT c.id, c.card_number, c.card_holder_name, c.card_type, c.expiration_date, c.balance, c.status, c.created_at, u.username, u.full_name FROM cards c JOIN users u ON c.user_id=u.id ORDER BY c.created_at DESC");
        $stmt->execute();
        $cards = $stmt->fetchAll(PDO::FETCH_ASSOC);

        http_response_code(200);
        echo json_encode($cards);
    }

    public function getAllLoans() {
        if (!$this->verifyAdmin()) {
            http_response_code(403);
            echo json_encode(["message" => "Forbidden."]);
            return;
        }

        $stmt = $this->db->prepare("SELECT l.*, u.username, u.full_name FROM loans l JOIN users u ON l.user_id=u.id ORDER BY l.created_at DESC");
        $stmt->execute();
        $loans = $stmt->fetchAll(PDO::FETCH_ASSOC);

        http_response_code(200);
        echo json_encode($loans);
    }

    public function updateLoanStatus($data) {
        $adminId = $this->verifyAdmin();
        if (!$adminId) {
            http_response_code(403);
            echo json_encode(["message" => "Forbidden."]);
            return;
        }

        if (empty($data->id) || empty($data->status)) {
            http_response_code(400);
            echo json_encode(["message" => "Loan ID and status required."]);
            return;
        }

        $stmt = $this->db->prepare("UPDATE loans SET status = ? WHERE id = ?");
        $stmt->execute([$data->status, $data->id]);
        $this->logAction($adminId, "Updated loan ID {$data->id} status to {$data->status}");

        http_response_code(200);
        echo json_encode(["message" => "Loan status updated."]);
    }

    public function getNotes() {
        $adminId = $this->verifyAdmin();
        if (!$adminId) {
            http_response_code(403);
            echo json_encode(["message" => "Forbidden."]);
            return;
        }

        $stmt = $this->db->prepare("SELECT * FROM admin_notes WHERE admin_id = ? ORDER BY updated_at DESC");
        $stmt->execute([$adminId]);
        $notes = $stmt->fetchAll(PDO::FETCH_ASSOC);

        http_response_code(200);
        echo json_encode($notes);
    }

    public function createNote($data) {
        $adminId = $this->verifyAdmin();
        if (!$adminId) {
            http_response_code(403);
            echo json_encode(["message" => "Forbidden."]);
            return;
        }

        if (empty($data->title) || empty($data->content)) {
            http_response_code(400);
            echo json_encode(["message" => "Title and content required."]);
            return;
        }

        $color = isset($data->color) ? $data->color : 'blue';

        $stmt = $this->db->prepare("INSERT INTO admin_notes (admin_id, title, content, color) VALUES (?, ?, ?, ?)");
        $stmt->execute([$adminId, $data->title, $data->content, $color]);

        $noteId = $this->db->lastInsertId();
        $stmt = $this->db->prepare("SELECT * FROM admin_notes WHERE id = ?");
        $stmt->execute([$noteId]);
        $note = $stmt->fetch(PDO::FETCH_ASSOC);

        http_response_code(201);
        echo json_encode(["message" => "Note created.", "note" => $note]);
    }

    public function updateNote($data) {
        $adminId = $this->verifyAdmin();
        if (!$adminId) {
            http_response_code(403);
            echo json_encode(["message" => "Forbidden."]);
            return;
        }

        if (empty($data->id)) {
            http_response_code(400);
            echo json_encode(["message" => "Note ID required."]);
            return;
        }

        $fields = [];
        $params = [];

        if (isset($data->title)) { $fields[] = "title = ?"; $params[] = $data->title; }
        if (isset($data->content)) { $fields[] = "content = ?"; $params[] = $data->content; }
        if (isset($data->color)) { $fields[] = "color = ?"; $params[] = $data->color; }

        if (empty($fields)) {
            http_response_code(400);
            echo json_encode(["message" => "Nothing to update."]);
            return;
        }

        $params[] = $data->id;
        $params[] = $adminId;
        $stmt = $this->db->prepare("UPDATE admin_notes SET " . implode(', ', $fields) . " WHERE id = ? AND admin_id = ?");
        $stmt->execute($params);

        http_response_code(200);
        echo json_encode(["message" => "Note updated."]);
    }

    public function deleteNote($data) {
        $adminId = $this->verifyAdmin();
        if (!$adminId) {
            http_response_code(403);
            echo json_encode(["message" => "Forbidden."]);
            return;
        }

        if (empty($data->id)) {
            http_response_code(400);
            echo json_encode(["message" => "Note ID required."]);
            return;
        }

        $stmt = $this->db->prepare("DELETE FROM admin_notes WHERE id = ? AND admin_id = ?");
        $stmt->execute([$data->id, $adminId]);

        http_response_code(200);
        echo json_encode(["message" => "Note deleted."]);
    }

    public function getSettings() {
        if (!$this->verifyAdmin()) {
            http_response_code(403);
            echo json_encode(["message" => "Forbidden."]);
            return;
        }

        $stmt = $this->db->query("SELECT setting_key, setting_value FROM admin_settings");
        $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

        $settings = [];
        foreach ($rows as $row) {
            $settings[$row['setting_key']] = $row['setting_value'];
        }

        http_response_code(200);
        echo json_encode($settings);
    }

    public function updateSettings($data) {
        $adminId = $this->verifyAdmin();
        if (!$adminId) {
            http_response_code(403);
            echo json_encode(["message" => "Forbidden."]);
            return;
        }

        $data = (array) $data;

        foreach ($data as $key => $value) {
            $stmt = $this->db->prepare("INSERT INTO admin_settings (setting_key, setting_value) VALUES (?, ?) ON DUPLICATE KEY UPDATE setting_value = ?");
            $stmt->execute([$key, $value, $value]);
        }

        $this->logAction($adminId, "Updated system settings");

        http_response_code(200);
        echo json_encode(["message" => "Settings updated."]);
    }

    public function getLogs() {
        if (!$this->verifyAdmin()) {
            http_response_code(403);
            echo json_encode(["message" => "Forbidden."]);
            return;
        }

        $stmt = $this->db->prepare("SELECT l.id, l.action, l.created_at, u.username FROM admin_logs l JOIN users u ON l.user_id=u.id ORDER BY l.created_at DESC LIMIT 100");
        $stmt->execute();
        $logs = $stmt->fetchAll(PDO::FETCH_ASSOC);

        http_response_code(200);
        echo json_encode($logs);
    }
}
?>
