<?php

namespace App\Http\Controllers;

use App\Http\Traits\StringGeneratorTrait;
use Ramsey\Uuid\Uuid;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
use App\Models\WebForm;
use Illuminate\Support\Facades\Schema;
use Exception;

class AdminController extends Controller
{
  use StringGeneratorTrait;

  public function index()
  {
    $records = WebForm::orderBy('created_at', 'DESC')->paginate(30);
    return view('app.admin.index', compact('records'));
  }
  public function login()
  {
    return view('app.admin.login');
  }

  public function submitLogin(Request $request)
  {
    $request->validate([
      'username' => 'required|string',
      'password' => 'required|string'
    ]);

    $username = $request->get('username');
    $password = $request->get('password');

    $expectedUsername = config('app.adminSessionUsername');
    $expectedPassword = config('app.adminSessionPassword');

    if ($username !== $expectedUsername && $password !== $expectedPassword) {
      return redirect()->back()->with('error', 'Invalid credentials!');
    }

    $request->session()->put('adminSession', rand());

    return redirect()->to(route('admin.index'));
  }
  public function logout(Request $request)
  {
    if (!$request->session()->exists('adminSession')) {
      return redirect()->to(route('login'));
    }
    $request->session()->forget('adminSession');
    return redirect()->to(route('admin.index'));
  }

  public function mygrateOldForms(Request $request)
  {
    $dateFilter = '2022-12-14';
    $tables = [
      'patient_find_a_clinic_request' => 'patient_find_a_clinic',
      'patient_contact_message' => 'patient_contact_message',
      'physician_training_request' => 'physician_training_request',
      'physician_contact_message' => 'physician_contact_message',
      'physician_directory_listing_request' => 'physician_directory_listing_request',
      'physician_marketing_materials_request' => 'physician_marketing_materials_request',
      'ligator_order' => 'physician_ligator_order'
    ];

    try {
      foreach ($tables as $table => $formName) {
        if(!Schema::hasTable($table)) continue;
        $records = DB::select(DB::raw("SELECT * FROM $table WHERE DATE(created_at) <= '" . $dateFilter . "'"));
        $excludes = ['id', 'uid', 'iid', 'created_at', 'updated_at'];
        foreach ($records as $record) {
          $record = array_diff_key((array)$record, array_flip($excludes));
          $this->migrateTableRecordToWebFormTable($record, $formName);
          Schema::dropIfExists($table);
        }
      }
      dd('Migrated!');
    } catch (Exeception $error) {
      dd($error->getMessage());
    }
  }

  private function migrateTableRecordToWebFormTable($record, $formName)
  {
    $record = new WebForm;
    $record->iid = $this->makeIID();
    $record->uid = Uuid::uuid6();
    $record->form_name = $formName;
    $record->form_data = json_encode($record);
    $record->save();
  }
}
