<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\DB;
use Validator;
use Hidehalo\Nanoid\Client as Nanoid;
use Hidehalo\Nanoid\GeneratorInterface as NanoidInterface;
use App\Responses;
use App\Helper;
use App\Models\Clients;
use App\Models\PocketMoney;
use App\Models\Checkpoints;
use App\Models\Zone;

class PocketController extends Controller
{
	/**
	 * View
	 */

	public function view_pockets(Request $req)
	{
		$data = [
			'types' => PocketMoney::getTypes(),
			'flows' => PocketMoney::getFlows(),
			// 'clients' => Clients::listClients(['c_status' => Clients::CSTTS_ACTIVE]),
      // 'pickups' => Zone::listZones($req->auth, ['is_active' => Zone::STATUS_ACTIVE, 'type' => Zone::ZONE_TYPE_WAREHOUSE, 'workflow_type' => Zone::ZONE_WORKFLOW_PICKUP]),
      // 'drops' => Zone::listZones($req->auth, ['is_active' => Zone::STATUS_ACTIVE, 'type' => Zone::ZONE_TYPE_WAREHOUSE, 'workflow_type' => Zone::ZONE_WORKFLOW_DEST]),
		];

		return view('menu_v1.configs.pocket_money', $data);
	}


	/**
	 * API
	 */

	public function api_list_pockets(Request $req)
	{
		try {
			$now = time();
			$input = [
				'cptid' => $req->cptid,
			];
			$rulesInput = [
				'cptid' => 'nullable|numeric'
			];

			// validasi input
			$isValidInput = Validator::make($input, $rulesInput);
			if (!$isValidInput->passes()) {
				$apiResp = Responses::bad_input($isValidInput->messages()->first());
				return new Response($apiResp, $apiResp['meta']['code']);
			}
			$filter = [];
			if ($input['cptid'] != null && $input['cptid'] != 0) {
				$filter['cptid'] = $input['cptid'];
			}

			$list = PocketMoney::listPockets($filter);
			foreach ($list as $key => $row) {
				$list[$key]->DT_RowIndex = $key + 1;
				$list[$key]->action = '-';
			}

			$apiResp = Responses::success('success list pockets');
			$apiResp['count'] = count($list);
			$apiResp['data'] = $list;
			return (new Response($apiResp, $apiResp['meta']['code']));
		} catch (\Exception $e) {
			$apiResp = Responses::error($e->getMessage());
			return (new Response($apiResp, $apiResp['meta']['code']));
		}
	}

	public function api_show_pocket(Request $req, $pocket_id)
	{
		try {
			$now = time();

			$input = [
				'pocket_id' => $pocket_id,
			];
			$rulesInput = [
				'pocket_id' => 'required|integer|not_in:0',
			];

			// validasi input
			$isValidInput = Validator::make($input, $rulesInput);
			if (!$isValidInput->passes()) {
				$apiResp = Responses::bad_input($isValidInput->messages()->first());
				return new Response($apiResp, $apiResp['meta']['code']);
			}

			$pocket = PocketMoney::showPocketById($pocket_id);
			if (count($pocket) < 1) {
				$apiResp = Responses::not_found('pocket not found');
				return (new Response($apiResp, $apiResp['meta']['code']));
			}

      $pocket[0]->checkpoints = Checkpoints::listCheckpoints(['pocket_id' => $pocket[0]->id]);
			
			$apiResp = Responses::success('success get detail pocket');
			$apiResp['data'] = $pocket[0];
			return (new Response($apiResp, $apiResp['meta']['code']));
		} catch (\Exception $e) {
			$apiResp = Responses::error($e->getMessage());
			return (new Response($apiResp, $apiResp['meta']['code']));
		}
	}

	public function api_add_pocket(Request $req)
	{
		try {
			$now = time();

			$input = [
				'name' => $req->add_name,
				'type' => $req->add_type,
				'pck' => $req->add_pck,
				'drop' => $req->add_drop,
				'price' => $req->add_price,
				'start_checkpoint' => $req->add_start_checkpoints,
				// 'end_checkpoint' => $req->add_end_checkpoints,
				'price_checkpoint' => $req->add_price_checkpoints,
				'status' => $req->status,
			];
			$rulesInput = [
				'name' => 'required|string|max:255',
				'type' => 'required|numeric|min:0',
				'pck' => 'required|numeric|min:0',
				'drop' => 'required|numeric|min:0',
				'price' => 'required|numeric|min:0',
				'start_checkpoint' => 'nullable|array',
				'start_checkpoint.*' => 'nullable|numeric|min:0',
				// 'end_checkpoint' => 'nullable|array',
				// 'end_checkpoint.*' => 'nullable|numeric|min:0',
				'price_checkpoint' => 'nullable|array',
				'price_checkpoint.*' => 'nullable|numeric|min:0',
				'status' => 'required|numeric|min:0',
			];

			// validasi input
			$isValidInput = Validator::make($input, $rulesInput);
			if (!$isValidInput->passes()) {
				$apiResp = Responses::bad_input($isValidInput->messages()->first());
				return new Response($apiResp, $apiResp['meta']['code']);
			}

			$nanoid = new Nanoid();
			$code = $nanoid->formattedId('0123456789', 9);
			// $code = $now;
			$doWhile = true;
			do {
				if (substr($code, 0, 1) == 0) {
					$code = $nanoid->formattedId('0123456789', 9);
				} else {
					$doWhile = false;
				}
			} while ($doWhile);
			$uniqCode = PocketMoney::getPocketByCode($code);
			if (count($uniqCode) > 0) {
				$apiResp = Responses::bad_request('code has been used, try again');
				return (new Response($apiResp, $apiResp['meta']['code']));
			}

      // $uniqPckDrop = PocketMoney::getPocketByPckDrop($input['pck'], $input['drop']);
			// if (count($uniqPckDrop) > 0) {
			// 	$apiResp = Responses::bad_request('Pickup dan Drop sudah pernah ditambahkan');
			// 	return (new Response($apiResp, $apiResp['meta']['code']));
			// }

      if ($input['start_checkpoint']) {
        if ($input['start_checkpoint'][0] != $input['pck']) {
          $apiResp = Responses::bad_request('Titik lokasi pertama checkpoint haruslah sama dengan pickup');
				  return (new Response($apiResp, $apiResp['meta']['code']));
        }
      }

			$pck = Zone::showZoneById($input['pck']);
			if (count($pck) < 1) {
				$apiResp = Responses::not_found('lokasi pickup tidak ditemukan');
				return (new Response($apiResp, $apiResp['meta']['code']));	
			}
			$drop = Zone::showZoneById($input['drop']);
			if (count($drop) < 1) {
				$apiResp = Responses::not_found('lokasi drop tidak ditemukan');
				return (new Response($apiResp, $apiResp['meta']['code']));	
			}

			if ($pck[0]->client_group_id !== $drop[0]->client_group_id) {
				$apiResp = Responses::bad_request('Lokasi pickup dan drop sudah beda perusahaan');
				return (new Response($apiResp, $apiResp['meta']['code']));	
			}

			DB::beginTransaction();

			$insPocket = [
				'code' => $code,
				'name' => $input['name'],
				'type' => $input['type'],
        'flow' => PocketMoney::FLOW_HYBRID,
				'pck_id' => $input['pck'],
				'drop_id' => $input['drop'],
				'is_active' => $input['status'],
				'total' => 0,
				'crt' => $now,
				'crt_by' => $req->auth->uid,
				'updt' => $now,
				'updt_by' => $req->auth->uid,
			];
			$pocket_id = PocketMoney::addPocket($insPocket);

			$total = 0;
      if ($input['start_checkpoint']) {
        foreach ($input['start_checkpoint'] as $i => $row) {
          $insCheckpoint = [
            'pocket_id' => $pocket_id,
            'pck_id' => $input['start_checkpoint'][$i],
            // 'drop_id' => $input['end_checkpoint'][$i],
            'total' => $input['price_checkpoint'][$i],
            'sort' => $i + 1,
            'crt' => $now,
            'crt_by' => $req->auth->uid,
            'updt' => $now,
            'updt_by' => $req->auth->uid,
          ];
					$total += $input['price_checkpoint'][$i];
          Checkpoints::addCheckpoint($insCheckpoint);
        }
			} else {
        $insCheckpoint = [
          'pocket_id' => $pocket_id,
          'pck_id' => $input['pck'],
          'drop_id' => $input['drop'],
          'total' => $input['price'],
          'sort' => 1,
          'crt' => $now,
          'crt_by' => $req->auth->uid,
          'updt' => $now,
          'updt_by' => $req->auth->uid,
        ];
				$total += $input['price'];
        Checkpoints::addCheckpoint($insCheckpoint);
      }

			PocketMoney::updatePocket($pocket_id, ['total' => $total]);

			$apiResp = Responses::created('success add new pocket');

			DB::commit();
			return (new Response($apiResp, $apiResp['meta']['code']));
		} catch (\Exception $e) {
			DB::rollBack();
			$apiResp = Responses::error($e->getMessage());
			return (new Response($apiResp, $apiResp['meta']['code']));
		}
	}

	public function api_edit_pocket(Request $req, $pocket_id)
	{
		try {
			$now = time();

			$input = [
        'pocket_id' => $pocket_id,
				'name' => $req->updt_name,
				'type' => $req->updt_type,
				'pck' => $req->updt_pck,
				'drop' => $req->updt_drop,
				'price' => $req->updt_price,
				'start_checkpoint' => $req->updt_start_checkpoints,
				// 'end_checkpoint' => $req->updt_end_checkpoints,
				'price_checkpoint' => $req->updt_price_checkpoints,
				'status' => $req->status,
			];
			$rulesInput = [
        'pocket_id' => 'required|integer|not_in:0',
				'name' => 'required|string|max:255',
				'type' => 'required|numeric|min:0',
				'pck' => 'required|numeric|min:0',
				'drop' => 'required|numeric|min:0',
				'price' => 'required|numeric|min:0',
				'start_checkpoint' => 'nullable|array',
				'start_checkpoint.*' => 'nullable|numeric|min:0',
				// 'end_checkpoint' => 'nullable|array',
				// 'end_checkpoint.*' => 'nullable|numeric|min:0',
				'price_checkpoint' => 'nullable|array',
				'price_checkpoint.*' => 'nullable|numeric|min:0',
				'status' => 'required|numeric|min:0',
			];

			// validasi input
			$isValidInput = Validator::make($input, $rulesInput);
			if (!$isValidInput->passes()) {
				$apiResp = Responses::bad_input($isValidInput->messages()->first());
				return new Response($apiResp, $apiResp['meta']['code']);
			}

			$pocket = PocketMoney::showPocketById($pocket_id);
			if (count($pocket) < 1) {
				$apiResp = Responses::not_found('pocket not found');
				return (new Response($apiResp, $apiResp['meta']['code']));
			}

      $pocket[0]->checkpoints = Checkpoints::listCheckpoints(['pocket_id' => $pocket[0]->id]);

      if ($input['start_checkpoint']) {
        if ($input['start_checkpoint'][0] != $input['pck']) {
          $apiResp = Responses::bad_request('Titik lokasi pertama checkpoint haruslah sama dengan pickup');
				  return (new Response($apiResp, $apiResp['meta']['code']));
        }
      }

			$pck = Zone::showZoneById($input['pck']);
			if (count($pck) < 1) {
				$apiResp = Responses::not_found('lokasi pickup tidak ditemukan');
				return (new Response($apiResp, $apiResp['meta']['code']));	
			}
			$drop = Zone::showZoneById($input['drop']);
			if (count($drop) < 1) {
				$apiResp = Responses::not_found('lokasi drop tidak ditemukan');
				return (new Response($apiResp, $apiResp['meta']['code']));	
			}

			if ($pck[0]->client_group_id !== $drop[0]->client_group_id) {
				$apiResp = Responses::bad_request('Lokasi pickup dan drop sudah beda perusahaan');
				return (new Response($apiResp, $apiResp['meta']['code']));	
			}

			DB::beginTransaction();

			$updtPocket = [
        // 'code' => $code,
				'type' => $input['type'],
				'name' => $input['name'],
        // 'flow' => PocketMoney::FLOW_HYBRID,
				'pck_id' => $input['pck'],
				'drop_id' => $input['drop'],
				'is_active' => $input['status'],
				'total' => 0,
				'updt' => $now,
				'updt_by' => $req->auth->uid,
			];
			PocketMoney::updatePocket($input['pocket_id'], $updtPocket);

			$total = 0;
      if ($input['start_checkpoint']) {
        Checkpoints::deleteCheckpointByPocketId($input['pocket_id']);
        foreach ($input['start_checkpoint'] as $i => $row) {
          $insCheckpoint = [
            'pocket_id' => $input['pocket_id'],
            'pck_id' => $input['start_checkpoint'][$i],
            // 'drop_id' => $input['end_checkpoint'][$i],
            'total' => $input['price_checkpoint'][$i],
            'sort' => $i + 1,
            'crt' => $now,
            'crt_by' => $req->auth->uid,
            'updt' => $now,
            'updt_by' => $req->auth->uid,
          ];
					$total += $input['price_checkpoint'][$i];
          Checkpoints::addCheckpoint($insCheckpoint);
        }
			} else {
        Checkpoints::deleteCheckpointByPocketId($input['pocket_id']);
        $updtCheckpoint = [
          'pocket_id' => $input['pocket_id'],
          'pck_id' => $input['pck'],
          'drop_id' => $input['drop'],
          'total' => $input['price'],
          'sort' => 1,
          'crt' => $now,
          'crt_by' => $req->auth->uid,
          'updt' => $now,
          'updt_by' => $req->auth->uid,
        ];
				$total += $input['price'];
        // Checkpoints::updateCheckpoint($pocket[0]->checkpoints[0]->id, $updtCheckpoint);
        Checkpoints::addCheckpoint($updtCheckpoint);
      }

			PocketMoney::updatePocket($input['pocket_id'], ['total' => $total]);

			$apiResp = Responses::created('success update pocket');

			DB::commit();
			return (new Response($apiResp, $apiResp['meta']['code']));
		} catch (\Exception $e) {
			DB::rollBack();
			$apiResp = Responses::error($e->getMessage());
			return (new Response($apiResp, $apiResp['meta']['code']));
		}
	}

	public function api_del_pocket(Request $req, $pocket_id)
	{
		try {
			$now = time();

			$input = [
				'pocket_id' => $pocket_id,
			];
			$rulesInput = [
				'pocket_id' => 'required|integer|not_in:0',
			];

			// validasi input
			$isValidInput = Validator::make($input, $rulesInput);
			if (!$isValidInput->passes()) {
				$apiResp = Responses::bad_input($isValidInput->messages()->first());
				return new Response($apiResp, $apiResp['meta']['code']);
			}

			$pocket = PocketMoney::showPocketById($pocket_id);
			if (count($pocket) < 1) {
				$apiResp = Responses::not_found('pocket not found');
				return (new Response($apiResp, $apiResp['meta']['code']));
			}
      $pocket[0]->checkpoints = Checkpoints::listCheckpoints(['pocket_id' => $pocket[0]->id]);

			DB::beginTransaction();

			PocketMoney::updatePocket($pocket_id, [
				'dlt' => $now,
				'dlt_by' => $req->auth->uid,
			]);

      foreach ($pocket[0]->checkpoints as $row) {
        Checkpoints::updateCheckpoint($row->id, [
          'dlt' => $now,
          'dlt_by' => $req->auth->uid,
        ]);
      }

			DB::commit();
			
			$apiResp = Responses::success('success delete pocket');
			return (new Response($apiResp, $apiResp['meta']['code']));
		} catch (\Exception $e) {
			DB::rollBack();
			$apiResp = Responses::error($e->getMessage());
			return (new Response($apiResp, $apiResp['meta']['code']));
		}
	}

	public function api_pck_drop_pocket(Request $req)
	{
		try {
			$now = time();

			$input = [
				'client_id' => $req->client_id,
				'pck_id' => $req->pck_id,
				'drop_id' => $req->drop_id,
			];
			$rulesInput = [
				'client_id' => 'required|integer|not_in:0',
				'pck_id' => 'required|integer|not_in:0',
				'drop_id' => 'required|integer|not_in:0',
			];

			// validasi input
			$isValidInput = Validator::make($input, $rulesInput);
			if (!$isValidInput->passes()) {
				$apiResp = Responses::bad_input($isValidInput->messages()->first());
				return new Response($apiResp, $apiResp['meta']['code']);
			}

			$pockets = PocketMoney::listPockets([
				'cptid' => $input['client_id'],
				'pck_id' => $input['pck_id'],
				'drop_id' => $input['drop_id'],
				'is_active' => PocketMoney::IS_ACTIVE,
			]);
			if (count($pockets) < 1) {
				$apiResp = Responses::not_found('pocket not found');
				return (new Response($apiResp, $apiResp['meta']['code']));
			}

			foreach ($pockets as $i => $pkt) {
				$pockets[$i]->checkpoints = Checkpoints::listCheckpoints(['pocket_id' => $pkt->id]);
			}
			
			$apiResp = Responses::success('success get pockets');
			$apiResp['data'] = $pockets;
			return (new Response($apiResp, $apiResp['meta']['code']));
		} catch (\Exception $e) {
			$apiResp = Responses::error($e->getMessage());
			return (new Response($apiResp, $apiResp['meta']['code']));
		}
	}
}
