<?php

namespace App\Modules\Admin;

use Illuminate\Support\Facades\View;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Session;
use Exception;
use App\Http\Controllers\BaseController;
use Illuminate\Http\Request;

class RestController extends BaseController
{
    /**
     *	The layout that should be used for responses.
     */
    protected $layout = 'layouts.master';

    /**
     * Render the ldap settings page.
     *
     * @return null
     */
    public function index()
    {
        $accounts = DB::table('oauth_clients')->get();

        $this->layout->content = View::make('admin::settings.rest.index', compact('accounts'));
    }

    /**
     * Display the page for creating a new rest.
     *
     * @return null
     */
    public function create()
    {
        $this->layout->content = View::make('admin::settings.rest.create');
    }

    /**
     * Creates a new rest.
     *
     * @return Illuminate\Support\Response
     */
    public function store(Request $request)
    {
        $data = $request->only('id', 'secret', 'name');
        
        // Check if ID already exists
        $existing = DB::table('oauth_clients')->where('id', $data['id'])->first();
        if ($existing) {
            return Redirect::route('admin.settings.rest.create')
                ->withInput()
                ->with('error', 'A REST client with this ID already exists. Please choose a different ID.');
        }
        
        $data['created_at'] = date('Y-m-d H:i:s');
        $data['updated_at'] = date('Y-m-d H:i:s');

        // Generate a random secret if not present
        if (! $data['secret']) {
            $data['secret'] = str_random(40);
        }

        // Insert data into the table
        try {
            $rows = DB::table('oauth_clients')->insert($data);
            
            if (! $rows) {
                return Redirect::route('admin.settings.rest.create')->with('error', 'Failed to create the REST client.');
            }
            
            return Redirect::route('admin.settings.rest.index')->with('message', 'REST Client added successfully.');
        } catch (\Exception $e) {
            return Redirect::route('admin.settings.rest.create')
                ->withInput()
                ->with('error', 'Failed to create the REST client: ' . $e->getMessage());
        }
    }

    /**
     * Display the edit a rest client page.
     *
     * @param  int $id
     *
     * @return null
     */
    public function edit($id)
    {
        $rest = DB::table('oauth_clients')->where('id', $id)->first();
        $this->layout->content = View::make('admin::settings.rest.edit', compact('rest'));
    }

    /**
     * Updates an existing rest client.
     *
     * @param  int $id
     *
     * @return null
     */
    public function update(Request $request, $id)
    {
        $data = $request->only('id', 'secret', 'name');
        $data['updated_at'] = date('Y-m-d H:i:s');

        // Generate a random secret if not present
        if (! $data['secret']) {
            $data['secret'] = str_random(40);
        }

        $rows = DB::table('oauth_clients')->where('id', $id)->update($data);

        if (! $rows) {
            return Redirect::route('admin.settings.rest.edit', $id)->with('error', 'Failed to update the REST Client.');
        }

        return Redirect::route('admin.settings.rest.edit', $data['id'])->with('message', 'Your changes were successfully saved.');
    }

    /**
     * Delete an rest client.
     *
     * @param  string $id
     *
     * @return array
     */
    public function destroy($id)
    {
        $rows = DB::table('oauth_clients')->where('id', $id)->delete();

        if (! $rows) {
            throw new Exception('Failed to delete the REST Client');
        }

        Session::flash('message', 'The REST Client <em><strong>'.$id.'</strong></em> has been successfully deleted');

        return ['success' => true];
    }
}
