<?php

use App\Http\Controllers\LoginController;
use App\Http\Controllers\Api\UtilityController;

/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the controller to call when that URI is requested.
|
*/

// Removed duplicate search route - moved to after login routes

// ==================================================================
//
// LOGIN ROUTES
//
// ------------------------------------------------------------------
Route::get('login', [LoginController::class, 'getIndex'])->name('login')->middleware('guest');
Route::post('login', [LoginController::class, 'postIndex']);
Route::post('auth/validate', [LoginController::class, 'postValidate'])->name('auth.validate.post');
Route::get('logout', [UtilityController::class, 'logout']);

// 3CX Integration - Phone number search (public access)
Route::get('search', function() {
    // Log that the route was hit
    \Log::info('[3CX Search] Route accessed', [
        'url' => request()->fullUrl(),
        'method' => request()->method(),
        'user_agent' => request()->userAgent(),
        'ip' => request()->ip()
    ]);
    
    $number = request()->get('number');
    
    \Log::info('[3CX Search] Processing search request', [
        'number' => $number,
        'query_params' => request()->query()
    ]);
    
    if (empty($number)) {
        return response()->json([
            'success' => false,
            'message' => 'Phone number parameter is required'
        ], 400);
    }
    
    // Clean the number
    $cleanNumber = preg_replace('/[^0-9+]/', '', $number);
    
    try {
        // Debug: Check total clients in database
        $totalClients = DB::table('clients')->count();
        
        // Debug: Check clients with any phone data
        $clientsWithPhones = DB::table('clients')
            ->whereNotNull('phone')
            ->orWhereNotNull('mobile')
            ->count();
        
        // Search with exact match first
        $exactMatch = DB::table('clients')
            ->select('id', 'name', 'phone', 'mobile', 'email', 'company')
            ->where('phone', $cleanNumber)
            ->orWhere('mobile', $cleanNumber)
            ->first();
            
        if ($exactMatch) {
            return response()->json([
                'success' => true,
                'id' => $exactMatch->id,
                'name' => $exactMatch->name,
                'company' => $exactMatch->company,
                'phone' => $exactMatch->phone ?: $exactMatch->mobile,
                'email' => $exactMatch->email,
                'match_type' => 'exact'
            ]);
        }
        
        // Try partial match (like search)
        $partialMatch = DB::table('clients')
            ->select('id', 'name', 'phone', 'mobile', 'email', 'company')
            ->where(function($query) use ($cleanNumber) {
                $query->where('phone', 'like', '%' . $cleanNumber . '%')
                      ->orWhere('mobile', 'like', '%' . $cleanNumber . '%');
            })
            ->first();

        if ($partialMatch) {
            return response()->json([
                'success' => true,
                'id' => $partialMatch->id,
                'name' => $partialMatch->name,
                'company' => $partialMatch->company,
                'phone' => $partialMatch->phone ?: $partialMatch->mobile,
                'email' => $partialMatch->email,
                'match_type' => 'partial'
            ]);
        }
        
        // No match found - return debug info
        return response()->json([
            'success' => false,
            'message' => 'No matching contact found',
            'debug' => [
                'searched_number' => $number,
                'cleaned_number' => $cleanNumber,
                'total_clients' => $totalClients,
                'clients_with_phones' => $clientsWithPhones
            ]
        ], 404);
        
    } catch (\Exception $e) {
        return response()->json([
            'success' => false,
            'message' => 'Search error: ' . $e->getMessage()
        ], 500);
    }
});

Route::get('/env-debug', [UtilityController::class, 'envDebug']);




//OAUTH
Route::post('oauth/access_token', 'App\Http\Controllers\Api\OAuthController@accessToken');

Route::get('oauth/authorize', ['as' => 'oauth.authorize.get', 'middleware' => ['check-authorization-params', 'auth'], 'uses' => 'App\Http\Controllers\Api\OAuthController@authorizeGet']);

Route::post('oauth/authorize', ['as' => 'oauth.authorize.post', 'middleware' => ['csrf', 'check-authorization-params', 'auth'], 'uses' => 'App\Http\Controllers\Api\OAuthController@authorizePost']);

Route::post('dynamics/accounts', 'App\Http\Controllers\DynamicsCrmController@updateAccount');
Route::post('dynamics/contacts', 'App\Http\Controllers\DynamicsCrmController@updateContact');

// Duplicate route removed - moved to top of file

Route::group(['middleware' => 'auth:sanctum', 'prefix' => 'oauth'], function () {
    Route::get('me', 'App\Http\Controllers\Api\OAuthController@me');
    Route::get('tasks/untouched', 'App\Modules\Bookings\TaskControllerREST@untouched');
    Route::resource('tasks', 'App\Modules\Bookings\TaskControllerREST');
    Route::resource('devices', 'App\Modules\Bookings\DevicesControllerRESTv1', ['names' => [
        'index' => 'app.devices.index',
        'create' => 'app.devices.create',
        'store' => 'app.devices.store',
        'show' => 'app.devices.show',
        'edit' => 'app.devices.edit',
        'update' => 'app.devices.update',
        'destroy' => 'app.devices.destroy',
    ]]);
    Route::resource('users', 'App\Http\Controllers\api\v1\UsersControllerRESTv1', ['names' => [
        'index' => 'app.users.index',
        'create' => 'app.users.create',
        'store' => 'app.users.store',
        'show' => 'app.users.show',
        'edit' => 'app.users.edit',
        'update' => 'app.users.update',
        'destroy' => 'app.users.destroy',
    ]]);
    Route::resource('customers', App\Modules\Clients\controllers\api\v1\CustomersControllerREST::class, ['names' => [
        'index' => 'app.customers.index',
        'create' => 'app.customers.create',
        'store' => 'app.customers.store',
        'show' => 'app.customers.show',
        'edit' => 'app.customers.edit',
        'update' => 'app.customers.update',
        'destroy' => 'app.customers.destroy',
    ]]);
    Route::resource('sites', App\Modules\Clients\controllers\api\v1\SitesControllerREST::class, ['names' => [
        'index' => 'app.sites.index',
        'create' => 'app.sites.create',
        'store' => 'app.sites.store',
        'show' => 'app.sites.show',
        'edit' => 'app.sites.edit',
        'update' => 'app.sites.update',
        'destroy' => 'app.sites.destroy',
    ]]);
    Route::get('site-users', ['uses' => 'App\Modules\Clients\controllers\api\v1\SiteUsersControllerREST@all']);
    Route::resource('sites.users', App\Modules\Clients\controllers\api\v1\SiteUsersControllerREST::class, ['names' => [
        'index' => 'app.sites.users.index',
        'create' => 'app.sites.users.create',
        'store' => 'app.sites.users.store',
        'show' => 'app.sites.users.show',
        'edit' => 'app.sites.users.edit',
        'update' => 'app.sites.users.update',
        'destroy' => 'app.sites.users.destroy',
    ]]);
    Route::resource('parts', 'App\Modules\Bookings\controllers\api\v1\PartsControllerREST', ['names' => [
        'index' => 'app.parts.index',
        'create' => 'app.parts.create',
        'store' => 'app.parts.store',
        'show' => 'app.parts.show',
        'edit' => 'app.parts.edit',
        'update' => 'app.parts.update',
        'destroy' => 'app.parts.destroy',
    ]]);
    Route::resource('messages', 'App\Modules\Bookings\MessageControllerRESTv1', ['names' => [
        'index' => 'app.messages.index',
        'create' => 'app.messages.create',
        'store' => 'app.messages.store',
        'show' => 'app.messages.show',
        'edit' => 'app.messages.edit',
        'update' => 'app.messages.update',
        'destroy' => 'app.messages.destroy',
    ]]);
    Route::resource('stock/groups', 'App\Modules\Stock\StockGroupsControllerREST', ['names' => [
        'index' => 'app.stock.groups.index',
        'create' => 'app.stock.groups.create',
        'store' => 'app.stock.groups.store',
        'show' => 'app.stock.groups.show',
        'edit' => 'app.stock.groups.edit',
        'update' => 'app.stock.groups.update',
        'destroy' => 'app.stock.groups.destroy',
    ]]);
    Route::resource('stock', 'App\Modules\Stock\StockControllerRESTv1', ['names' => [
        'index' => 'app.stock.index',
        'create' => 'app.stock.create',
        'store' => 'app.stock.store',
        'show' => 'app.stock.show',
        'edit' => 'app.stock.edit',
        'update' => 'app.stock.update',
        'destroy' => 'app.stock.destroy',
    ]]);
    Route::resource('comments', 'App\Modules\Bookings\CommentControllerRESTv1', ['names' => [
        'index' => 'app.comments.index',
        'create' => 'app.comments.create',
        'store' => 'app.comments.store',
        'show' => 'app.comments.show',
        'edit' => 'app.comments.edit',
        'update' => 'app.comments.update',
        'destroy' => 'app.comments.destroy',
    ]]);
    Route::resource('statuses', 'App\Http\Controllers\api\v1\StatusControllerREST', ['names' => [
        'index' => 'app.statuses.index',
        'create' => 'app.statuses.create',
        'store' => 'app.statuses.store',
        'show' => 'app.statuses.show',
        'edit' => 'app.statuses.edit',
        'update' => 'app.statuses.update',
        'destroy' => 'app.statuses.destroy',
    ]]);
    Route::resource('severities', 'App\Http\Controllers\api\v1\SeverityControllerREST', ['names' => [
        'index' => 'app.severities.index',
        'create' => 'app.severities.create',
        'store' => 'app.severities.store',
        'show' => 'app.severities.show',
        'edit' => 'app.severities.edit',
        'update' => 'app.severities.update',
        'destroy' => 'app.severities.destroy',
    ]]);
    // Asterisk integration removed - replaced with 3CX module
    Route::resource('feedback', 'App\Modules\Bookings\TaskFeedbackControllerREST', ['only' => ['show', 'update'], 'names' => [
        'show' => 'app.feedback.show',
        'update' => 'app.feedback.update',
    ]]);
    Route::resource('channels', \App\Modules\Chat\controllers\api\v1\ChannelsControllerREST::class, ['only' => ['index'], 'names' => [
        'index' => 'app.channels.index',
    ]]);
    Route::post('users/profile-photo', ['uses' => 'App\Http\Controllers\api\v1\UsersControllerRESTv1@profilePhoto']);
    Route::post('files', ['uses' => 'App\Http\Controllers\api\v1\FilesControllerREST@upload']);
    Route::get('files/download/{id}', ['as' => 'oauth.files.download', 'uses' => 'App\Http\Controllers\api\v1\FilesControllerREST@download']);
    Route::get('files/{object}/{id}', ['uses' => 'App\Http\Controllers\api\v1\FilesControllerREST@get']);
    Route::get('files', ['uses' => 'App\Http\Controllers\api\v1\FilesControllerREST@index']);
    Route::get('files/{id}', ['uses' => 'App\Http\Controllers\api\v1\FilesControllerREST@show']);
    Route::delete('files/{id}', ['uses' => 'App\Http\Controllers\api\v1\FilesControllerREST@destroy']);

    Route::get('search', ['uses' => 'App\Http\Controllers\HomeController@search']);
    Route::resource('logs', 'App\Modules\Logs\LogControllerREST', ['only' => 'store', 'names' => [
        'store' => 'app.logs.store',
    ]]);
});

/* ------------------------------------------
* Route constraint patterns
* ------------------------------------------
*/
Route::pattern('keychain', '[0-9a-z_]+');
Route::pattern('files', '[0-9a-z]+');
Route::pattern('activity-logs', '[0-9a-z_]+');

// PDF Generation Routes (root level for frontend compatibility)
Route::middleware(['web', 'auth'])->group(function () {
    Route::get('generate-invoice/{id}', 'App\Http\Controllers\GenerateInvoicePdfController@generate');
});

/*
|--------------------------------------------------------------------------
| Pages that use the RESTFULL Api
|--------------------------------------------------------------------------
|
| This group routes are pages that return only JSON,
| and make use of the restfull controllers.
|
*/

Route::group(['prefix' => Config::get('app.api_path'), 'middleware' => ['web', 'auth']], function () {
    
    // PDF Generation Routes
    Route::get('generate-invoice/{id}', 'App\Http\Controllers\GenerateInvoicePdfController@generate');
    
    // Legacy KashFlow compatibility route (for any remaining API calls)
    Route::get('kashflow/print-invoice/{id}', 'App\Http\Controllers\GenerateInvoicePdfController@getPrintInvoice');
    
    
    Route::get('me', 'App\Http\Controllers\Api\UtilityController@me');
    Route::resource('settings', 'App\Http\Controllers\settings');
    Route::get('wotd','App\Http\Controllers\settings@wotd');
    Route::get('permissions', 'App\Http\Controllers\Api\UtilityController@permissions');
    Route::resource('calendar', 'App\Http\Controllers\api\v1\CalendarControllerRESTv1');
    Route::resource('sla', 'App\Http\Controllers\api\v1\SlaControllerREST');
    Route::resource('sla-logs', 'App\Http\Controllers\api\v1\SlaLogControllerREST');
    Route::post('users/profile-photo', 'App\Http\Controllers\api\v1\UsersControllerRESTv1@profilePhoto');
    Route::get('users/scores', 'App\Http\Controllers\api\v1\UsersControllerRESTv1@getScores');
    Route::resource('users', 'App\Http\Controllers\api\v1\UsersControllerRESTv1');
    
    // External API Safety Status
    Route::get('external-api/status', 'App\Http\Controllers\api\v1\ExternalApiStatusController@getStatus');
    Route::get('external-api/warnings', 'App\Http\Controllers\api\v1\ExternalApiStatusController@getWarnings');
    Route::post('external-api/test', 'App\Http\Controllers\api\v1\ExternalApiStatusController@testConnectivity');
    Route::post('external-api/settings', 'App\Http\Controllers\api\v1\ExternalApiStatusController@updateSettings');
    
    
    Route::resource('statuses', 'App\Http\Controllers\api\v1\StatusControllerREST');
    Route::resource('jophielHoliday', 'App\Http\Controllers\api\v1\jophielHolidayControllerRESTv1');
    Route::get('jophieldaysAllowed', 'App\Http\Controllers\api\v1\jophielHolidayControllerRESTv1@daysAllowed');

    
    Route::resource('jophielSickness', 'App\Http\Controllers\api\v1\jophielSicknessControllerRESTv1');
    # SMS
    Route::post('sms/send', 'App\Http\Controllers\api\v1\SMSControllerRESTv1@postSend');

    // Keychain
    Route::get('keychain/{client_type}/{client_id}', ['as' => 'keychain', 'uses' => 'App\Http\Controllers\api\v1\KeychainControllerREST@get']);
    Route::post('keychain/{client_type}/{client_id}', ['as' => 'keychain.create', 'uses' => 'App\Http\Controllers\api\v1\KeychainControllerREST@create']);
    Route::post('keychain/{id}', ['as' => 'keychain.update', 'uses' => 'App\Http\Controllers\api\v1\KeychainControllerREST@update']);
    // Files - Download route MUST come before {id} route to avoid conflicts
    Route::get('files/config', ['as' => 'files.config', 'uses' => 'App\Http\Controllers\api\v1\FilesControllerREST@config']);
    Route::post('files/upload', ['as' => 'files.upload', 'uses' => 'App\Http\Controllers\api\v1\FilesControllerREST@upload']);
    Route::get('files/download/{id}', ['as' => 'files.download', 'uses' => 'App\Http\Controllers\api\v1\FilesControllerREST@download']);
    Route::get('files/{object}/{id}', ['as' => 'files.get', 'uses' => 'App\Http\Controllers\api\v1\FilesControllerREST@get']);
    Route::get('files/{id}', ['as' => 'files.show', 'uses' => 'App\Http\Controllers\api\v1\FilesControllerREST@show']);
    Route::delete('files/{id}', ['uses' => 'App\Http\Controllers\api\v1\FilesControllerREST@destroy']);
    // Activity logs
    Route::get('activity-logs', ['as' => 'activity-logs.get', 'uses' => 'App\Http\Controllers\api\v1\ActivityLogsControllerREST@get']);
    Route::resource('follow', 'App\Http\Controllers\api\v1\FollowControllerREST');
    	// Asterisk integration removed - replaced with 3CX module
    
    // Severities
    Route::resource('severities', 'App\Http\Controllers\api\v1\SeverityControllerREST');

    Route::resource('api-tokens', 'App\Http\Controllers\Api\ApiTokenController', ['only' => ['index', 'store', 'destroy']]);

    Route::get('wiki/{id}', 'App\Http\Controllers\api\v1\jophielwikiControllerRESTv1@content');


});


/*
|--------------------------------------------------------------------------
| Pages rendered on the server
|--------------------------------------------------------------------------
|
| This group routes are pages rendered on the server.
| All the pages require the user to be authentificated.
|
*/

Route::get('/_debugbar/assets/stylesheets', [
    'as' => 'debugbar-css',
    'uses' => '\Barryvdh\Debugbar\Controllers\AssetController@css'
]);

Route::get('/_debugbar/assets/javascript', [
    'as' => 'debugbar-js',
    'uses' => '\Barryvdh\Debugbar\Controllers\AssetController@js'
]);

Route::get('/_debugbar/open', [
    'as' => 'debugbar-open',
    'uses' => '\Barryvdh\Debugbar\Controllers\OpenHandlerController@handle'
]);

Route::get('/debug-json', 'App\Http\Controllers\Api\UtilityController@debugJson');

Route::group(['middleware' => ['web', 'auth']], function () {
    // Office365 OAuth callback - moved to Admin module routes
    
    // Office365 calendars API route
    Route::get('api/v1/integrations/office365-calendars', 'App\Modules\Admin\IntegrationsController@getOffice365Calendars');
    
    
    // Dashboard routes
    Route::get('dial/{number}', 'App\Http\Controllers\HomeController@getDial');
    Route::get('switch-user/{user_id}', ['as' => 'switch-user', 'uses' => 'App\Http\Controllers\HomeController@switchUser']);
    Route::get('fixes/task-missing-site', ['as' => 'fixes.task-missing-site', 'uses' => 'App\Http\Controllers\HomeController@fixTasksMissingSite']);
    Route::get('search', ['as' => 'search', 'uses' => 'App\Http\Controllers\HomeController@search']);
    Route::get('emails/debug', 'App\Http\Controllers\Api\UtilityController@emailsDebug');
    Route::get('docs/general-repairs-guidelines', ['as' => 'docs.general-repairs-guidelines', 'uses' => 'App\Http\Controllers\TechDocsController@getGeneralRepairsGuidelines']);
    Route::get('docs/new-machine-checklist', ['as' => 'docs.new-machine-checklist', 'uses' => 'App\Http\Controllers\TechDocsController@getNewMachineChecklist']);
    Route::get('docs/technician-pricing-and-warranty', ['as' => 'docs.technician-pricing-and-warranty', 'uses' => 'App\Http\Controllers\TechDocsController@getTechnicianPricingAndWarranty']);
    Route::get('changelog', 'App\Http\Controllers\ChangeLogController@index');

    // Import routes removed - no longer needed

    // Last rule

    Route::get('/', 'App\Http\Controllers\HomeController@getIndex');
    Route::get('dial/{number}', 'App\Http\Controllers\HomeController@getDial');
    Route::get('search', 'App\Http\Controllers\HomeController@search');
    Route::get('switch-user/{user_id}', 'App\Http\Controllers\HomeController@switchUser');
    Route::get('fixes/task-missing-site', 'App\Http\Controllers\HomeController@fixTasksMissingSite');
});
