<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;


class BackUpController extends Controller
{
  public function index()
  {
    return view('system.backup');
  }

  public function backUp(Request $request)
  {
    $user = DB::table('user')
      ->where('u_email', $request->u_email)
      ->first();

    $pass = Hash::check($request->u_password, $user->u_password);

    if ($user->u_role == "Dokter" && $pass == 1 || $user->u_role == "Developer" && $pass == 1) {
      $get_all_table_query = "SHOW TABLES";
      $result = DB::select(DB::raw($get_all_table_query));

      $tables = [
        'antrian',
        'data_pasien'
      ];

      $structure = '';
      $data = '';
      foreach ($tables as $table) {
        $show_table_query = "SHOW CREATE TABLE " . $table . "";

        $show_table_result = DB::select(DB::raw($show_table_query));

        foreach ($show_table_result as $show_table_row) {
          $show_table_row = (array)$show_table_row;
          $structure .= "\n\n" . $show_table_row["Create Table"] . ";\n\n";
        }
        $select_query = "SELECT * FROM " . $table;
        $records = DB::select(DB::raw($select_query));

        foreach ($records as $record) {
          $record = (array)$record;
          $table_column_array = array_keys($record);
          foreach ($table_column_array as $key => $name) {
            $table_column_array[$key] = '`' . $table_column_array[$key] . '`';
          }

          $table_value_array = array_values($record);
          $data .= "\nINSERT INTO $table (";

          $data .= "" . implode(", ", $table_column_array) . ") VALUES \n";

          foreach ($table_value_array as $key => $record_column)
            $table_value_array[$key] = addslashes($record_column);

          $data .= "('" . wordwrap(implode("','", $table_value_array), 400, "\n", TRUE) . "');\n";
        }
      }

      $output = $structure . $data;

      $file_name = 'database_backup_on_' . date('y-m-d') . '.sql';
      $file_handle = fopen($file_name, 'w+');
      fwrite($file_handle, $output);
      fclose($file_handle);
      header('Content-Description: File Transfer');
      header('Content-Type: application/octet-stream');
      header('Content-Disposition: attachment; filename=' . basename($file_name));
      header('Content-Transfer-Encoding: binary');
      header('Expires: 0');
      header('Cache-Control: must-revalidate');
      header('Pragma: public');
      header('Content-Length: ' . filesize($file_name));
      ob_clean();
      flush();
      readfile($file_name);
      unlink($file_name);
      return view('system.backup')->with(['notif' => 'success']);
    } else {
      return redirect('backup')->with(['notif' => 'error']);
    };
  }
}
