<?php

namespace App\Http\Controllers\Api;

use Illuminate\Support\Facades\Request;
use Illuminate\Support\Facades\Response;
use Illuminate\Support\Facades\View;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\Controller;

class UtilityController extends Controller
{
    /**
     * Get current authenticated user
     */
    public function me()
    {
        return Auth::user();
    }

    /**
     * Get user permissions
     */
    public function permissions()
    {
        $user = Auth::user();
        return DB::select(
            'SELECT `groups`.name as "groups",`permissions`.name as "permissions" FROM `group_user` INNER JOIN `group_permissions` ON `group_user`.group_id=`group_permissions`.group_id INNER JOIN `groups` ON `groups`.id=`group_permissions`.group_id INNER JOIN `permissions` ON `permissions`.id=`group_permissions`.permission_id where `group_user`.`user_id` = ?',
            [$user->id]
        );
    }



    /**
     * Debug JSON view
     */
    public function debugJson()
    {
        return view('debug-json');
    }

    /**
     * Debug emails view
     */
    public function emailsDebug()
    {
        return View::make(request()->get('layout', 'emails.layouts.master'));
    }

    /**
     * Logout user
     */
    public function logout()
    {
        Auth::logout();
        session()->invalidate();
        session()->regenerateToken();

        return Redirect::to('login');
    }

    /**
     * Debug environment variables
     */
    public function envDebug()
    {
        return [
            'env(APP_ENV)' => env('APP_ENV'),
            'config(app.env)' => config('app.env'),
            '$_SERVER[APP_ENV]' => $_SERVER['APP_ENV'] ?? 'not set',
            '$_ENV[APP_ENV]' => $_ENV['APP_ENV'] ?? 'not set',
            'getenv(APP_ENV)' => getenv('APP_ENV'),
        ];
    }

    /**
     * Display a listing of the resource.
     *
     * @return Response
     */
    public function index()
    {
        return Response::json(['message' => 'Utility controller']);
    }

    /**
     * Send an email using a template
     *
     * @return Response
     */
    public function sendEmail()
    {
        $data = request()->all();
        
        if (!isset($data['to']) || !isset($data['subject']) || !isset($data['template'])) {
            return Response::json(['error' => 'Missing required fields'], 400);
        }

        $layout = request()->get('layout', 'emails.layouts.master');
        
        try {
            Mail::send($data['template'], $data, function ($message) use ($data) {
                $message->to($data['to'])
                        ->subject($data['subject']);
            });
            
            return Response::json(['success' => true, 'message' => 'Email sent successfully']);
        } catch (\Exception $e) {
            return Response::json(['error' => 'Failed to send email: ' . $e->getMessage()], 500);
        }
    }

    /**
     * Get database information
     *
     * @return Response
     */
    public function getDatabaseInfo()
    {
        try {
            $tables = DB::select('SHOW TABLES');
            $dbName = DB::connection()->getDatabaseName();
            
            return Response::json([
                'database' => $dbName,
                'tables' => count($tables),
                'connection' => DB::connection()->getName()
            ]);
        } catch (\Exception $e) {
            return Response::json(['error' => 'Database error: ' . $e->getMessage()], 500);
        }
    }

    /**
     * Test database connection
     *
     * @return Response
     */
    public function testDatabase()
    {
        try {
            DB::connection()->getPdo();
            return Response::json(['success' => true, 'message' => 'Database connection successful']);
        } catch (\Exception $e) {
            return Response::json(['error' => 'Database connection failed: ' . $e->getMessage()], 500);
        }
    }
} 