<?php

namespace App\Http\Controllers;

set_time_limit(0);
error_reporting(E_ALL);
ini_set('display_errors', '1');
ini_set('memory_limit', '512M');

use App\Modules\Bookings\Comment as Comment;
use App\Modules\Bookings\Repair as Repair;
use App\Modules\Bookings\Onsite as Onsite;
use App\Modules\Bookings\Support as Support;
use App\Modules\Bookings\Order as Order;
use App\Modules\Bookings\Message as Message;
use App\Modules\Clients\Client as Client;
use App\Modules\Clients\Customer as Customer;
use App\Modules\Clients\Site as Site;
use App\Modules\Clients\SiteUser as SiteUser;

class ImportController extends BaseController
{
    protected $seraph2;
    protected $staff = [];

    protected function initialize()
    {
        $this->seraph2 = DB::connection('seraph2');
    }

    public function getSyncClients()
    {
        $this->initialize();
        $clients = Client::all();

        foreach ($clients as $client) {
            $seraph_client = $this->seraph2->table('customers')->where('name', 'like', $client->name)->first();

            if (! $seraph_client) {
                echo 'ERROR: Seraph client "'.$client->name.'" not found<br>';
                continue;
            }

            $sites = $client->sites;
            if (count($sites)) {
                $site = $sites[0];

                if ($site->name == 'Main' && ($site->address == 0 || $site->address == 1 || $site->primary_phone == 0 || $site->primary_phone == 1)) {
                    $site->address = $seraph_client->address ?: '';
                    $site->address2 = $seraph_client->address2 ?: '';
                    $site->postcode = $seraph_client->postcode ?: '';
                    $site->primary_phone = $seraph_client->phone ?: '';

                    if ($site->save()) {
                        echo 'Site '.$site->id.' successfully saved<br>';
                    } else {
                        echo 'ERROR: Failed to save site '.$site->id.'<br>';
                    }
                } else {
                    echo 'Update not necessary for '.$client->name.' <br>';
                }
            }
        }
    }

    protected function migrateStaff()
    {
        $staff = $this->seraph2->table('staff')->get();
        foreach ($staff as &$value) {
            $user = new User();
            $user->first_name = $value->realname;
            $user->last_name = '';
            $user->password = '';
            $user->mobile = '';
            $user->username = $value->username;
            $user->email = $value->email || '';
            $user->account_type = 'ldap';

            if ($user->save()) {
                $value->new_id = $user->id;
            }
        }

        $this->staff = $staff;
    }

    protected function findStaff($id)
    {
        if ($id == 1) {
            return;
        }

        foreach ($this->staff as $key => $value) {
            if ($value->staffid == $id) {
                return $value->new_id;
            }
        }

        return 2;
    }

    protected function getRepairStatus($id)
    {
        switch ($id) {
            case 1: return 1;
            case 2: return 4;
            case 3: return 10;
            case 4: return 5;
            case 5: return 6;
            case 6: return 7;
            case 7: return 8;
            case 8: return 11;
            case 13: return 9;
        }

        return 10;
    }

    protected function getSupportStatus($id)
    {
        switch ($id) {
            case 1: return 1;
            case 2: return 4;
            case 3: return 10;
        }

        return 10;
    }

    protected function getOnsiteStatus($id)
    {
        switch ($id) {
            case 1: return 1;
            case 2: return 10;
            case 3: return 8;
            case 4: return 12;
        }

        return 10;
    }

    protected function getSeverity($id)
    {
        switch ($id) {
            case 1: return 1;
            case 2: return 2;
            case 3: return 3;
            case 4: return 4;
        }

        return 2;
    }

    protected function migrateRepairs($client_id, $new_id, $type = 'client', $site_id = null, $site_user_id = null)
    {
        $repairs = $this->seraph2->table('repairs')->where('custid', '=', $client_id)->get();

        foreach ($repairs as $key => $value) {
            $repair = new Repair();
            $repair->title = $value->machine;
            $repair->problem = $value->problem;
            $repair->client_id = $new_id;
            $repair->client_type = $type;
            $repair->severity_id = $this->getSeverity($value->priority);
            $repair->labour = $value->ramount || 0;
            $repair->pin = $value->pin;
            $repair->site_id = $site_id;
            $repair->site_user_id = $site_user_id;
            $repair->status_id = $this->getRepairStatus($value->status);
            $repair->created_by = $this->findStaff($value->bookedinby);
            $repair->seraph_id = $value->repairid;
            $repair->created_at = $value->bookedintime;
            $repair->updated_at = $value->lastupdated;

            if ($value->assignedto != 1) {
                $repair->assigned_to = $this->findStaff($value->assignedto);
            }

            if ($repair->save()) {
                $this->migrateRemarks($value->repairid, $repair->id, 1);
            } else {
                echo 'Repair '.$value->repairid;
                dd($repair->errors->all());
            }
        }
    }

    protected function migrateRemarks($repair_id, $related_id, $type = 1, $related_type = 'task')
    {
        $remarks = $this->seraph2->table('remarks')->where('jobid', '=', $repair_id)->where('type', '=', $type)->get();

        foreach ($remarks as $key => $value) {
            $comment = new Comment();
            $comment->related_id = $related_id;
            $comment->related_type = $related_type;
            $comment->message = $value->remark;
            $comment->created_by = $this->findStaff($value->staffid);

            $comment->save();
        }
    }

    protected function migrateCustomers($offset = 0, $limit = 1000)
    {
        $customers = $this->seraph2->table('customers')->skip($offset)->take($limit)->get();

        foreach ($customers as $key => $value) {
            if ($value->qbid || $value->iscompany) {
                // Business
                $client = Client::where('name', '=', $value->name)->first();
                if ($client) {
                    $site = $client->sites[0];
                    $site_user = $site->users[0];

                    $this->migrateRepairs($value->custid, $client->id, 'client', $site->id, $site_user->id);
                    $this->migrateOnsite($value->custid, $client->id, 'client', $site->id, $site_user->id);
                    $this->migrateSupport($value->custid, $client->id, 'client', $site->id, $site_user->id);
                    $this->migrateMessages($value->custid, $client->id, 'client', $site->id, $site_user->id);
                } else {
                    $client = new Client();
                    $client->name = $value->name;

                    if ($client->save()) {
                        $site = new Site();
                        $site->name = 'Main';
                        $site->client_id = $client->id;
                        $site->address = $value->address ?: '';
                        $site->address2 = $value->address2;
                        $site->postcode = $value->postcode ?: '';
                        $site->primary_phone = $value->phone ?: '';

                        if ($site->save()) {
                            $site_user = new SiteUser();
                            $site_user->site_id = $site->id;
                            $site_user->first_name = 'Main';
                            $site_user->last_name = 'User';
                            $site_user->email = (! empty($value->email)) ? $value->email : 'test@no-email.com';
                            $site_user->mobile = (! empty($value->mobile)) ? $value->mobile : '123';
                            $site_user->phone = $value->phone;
                            $site_user->authority = true;
                            $site_user->position = 'default';

                            if ($site_user->save()) {
                                $this->migrateRepairs($value->custid, $client->id, 'client', $site->id, $site_user->id);
                                $this->migrateOnsite($value->custid, $client->id, 'client', $site->id, $site_user->id);
                                $this->migrateSupport($value->custid, $client->id, 'client', $site->id, $site_user->id);
                                $this->migrateMessages($value->custid, $client->id, 'client', $site->id, $site_user->id);
                            }
                        }
                    } else {
                        dd($site->errors->all());
                    }
                }
            } else {
                $name = explode(' ', $value->name, 2);
                $value->email = str_replace(' ', '', $value->email);

                // Customer
                $client = new Customer();
                $client->first_name = (isset($name[0]) && ! empty($name[0])) ? $name[0] : '.';
                $client->last_name = (isset($name[1]) && ! empty($name[1])) ? $name[1] : '.';
                $client->email = (! empty($value->email)) ? $value->email : 'test@test.com';
                $client->phone = (! empty($value->phone)) ? $value->phone : '0';
                $client->mobile = $value->mobile;
                $client->address = $value->address ?: '';
                $client->address2 = $value->address2;
                $client->town = (! empty($value->town)) ? $value->town : 'NA';
                $client->county = $value->county;
                $client->postcode = (! empty($value->postcode)) ? $value->postcode : 'NA';

                if ($client->save()) {
                    $this->migrateRepairs($value->custid, $client->id, 'customer');
                    $this->migrateOnsite($value->custid, $client->id, 'customer');
                    $this->migrateSupport($value->custid, $client->id, 'customer');
                    $this->migrateMessages($value->custid, $client->id, 'customer');
                } else {
                    echo $value->name.' '.$value->custid;
                    dd($client->errors->all());
                }
            }
        }

        echo '<a href="'.URL::to('/import/'.($offset + $limit)).'">Next</a>';
    }

    protected function migrateMessages($client_id, $new_id, $type = 'client', $site_id = null, $site_user_id = null)
    {
        $messages = $this->seraph2->table('messages')->where('custid', '=', $client_id)->get();

        foreach ($messages as $key => $value) {
            $message = new Message();
            $message->client_id = $new_id;
            $message->client_type = $type;
            $message->site_user_id = $site_user_id;
            $message->assigned_to = $this->findStaff($value->msgfor);
            $message->message = $value->notes;
            $message->contact_number = '';
            $message->status = 'read';
            $message->created_by = $this->findStaff($value->takenby);
            $message->created_at = $value->takentime;

            if ($message->save()) {
                $this->migrateRemarks($value->messageid, $message->id, 2, 'message');
            }
        }
    }

    protected function migrateOnsite($client_id, $new_id, $type = 'client', $site_id = null, $site_user_id = null)
    {
        $onsites = $this->seraph2->table('onsite')->where('custid', '=', $client_id)->get();

        foreach ($onsites as $key => $value) {
            $onsite = new Onsite();
            $onsite->title = $value->Title;
            $onsite->problem = $value->Problem;
            $onsite->client_id = $new_id;
            $onsite->client_type = $type;
            $onsite->severity_id = 2;
            $onsite->site_id = $site_id;
            $onsite->site_user_id = $site_user_id;
            $onsite->status_id = $this->getOnsiteStatus($value->status);
            $onsite->time_spent = $value->timespent || 0;
            $onsite->labour = $value->ramount || 0;
            $onsite->onsite_start = $value->StartDate;
            $onsite->onsite_end = $value->EndDate;
            $onsite->created_by = $this->findStaff($value->bookedinby);
            $onsite->updated_at = $value->lastupdated;

            if ($value->assignedto != 1) {
                $onsite->assigned_to = $this->findStaff($value->assignedto);
            }

            if ($onsite->save()) {
                $this->migrateRemarks($value->Id, $onsite->id, 7);
            } else {
                echo 'Onsite '.$value->Id;
                dd($onsite->errors->all());
            }
        }
    }

    protected function migrateSupport($client_id, $new_id, $type = 'client', $site_id = null, $site_user_id = null)
    {
        $supports = $this->seraph2->table('support')->where('custid', '=', $client_id)->get();

        foreach ($supports as $key => $value) {
            $support = new Support();
            $support->title = 'Seraph2 support';
            $support->problem = $value->notes;
            $support->client_id = $new_id;
            $support->client_type = $type;
            $support->severity_id = $this->getSeverity($value->priority);
            $support->status_id = $this->getSupportStatus($value->status);
            $support->site_id = $site_id;
            $support->site_user_id = $site_user_id;
            $support->time_spent = (! empty($value->time)) ? $value->time : 0;
            $support->created_by = $this->findStaff($value->bookedinby);
            $support->created_at = $value->bookedintime;
            $support->updated_at = $value->lastupdated;

            if ($value->assignedto != 1) {
                $support->assigned_to = $this->findStaff($value->assignedto);
            }

            if ($support->save()) {
                $this->migrateRemarks($value->supportid, $support->id, 3);
            } else {
                echo 'Support '.$value->Id;
                dd($support->errors->all());
            }
        }
    }

    protected function migrateOrders($client_id, $new_id, $type = 'client', $site_id = null, $site_user_id = null)
    {
        $orders = $this->seraph2->table('orders')->where('custid', '=', $client_id)->get();

        foreach ($orders as $key => $value) {
            $order = new Order();
            $order->title = $value->partname;
            $order->problem = $value->notes;
            $order->client_id = $new_id;
            $order->client_type = $type;
            $order->severity_id = 2;
            $order->status_id = $this->getRepairStatus($value->orderstatus);
            $order->site_id = $site_id;
            $order->site_user_id = $site_user_id;
            $order->created_by = $this->findStaff($value->requestedby);
            $order->created_at = $value->bookedintime;

            if ($value->assignedto != 1) {
                $order->assigned_to = $this->findStaff($value->assignedto);
            }

            if ($order->save()) {
                $this->migrateRemarks($value->orderid, $order->id, 5);
            } else {
                echo 'Orders '.$value->Id;
                dd($order->errors->all());
            }
        }
    }

    protected function cacheStaff()
    {
        $seraph_staff = $this->seraph2->table('staff')->get();
        $local_staff = User::all();

        foreach ($seraph_staff as &$value) {
            foreach ($local_staff as $u) {
                if ($u->username == $value->username) {
                    $value->new_id = $u->id;
                    break;
                }
            }
        }

        $this->staff = $seraph_staff;
    }

    public function getIndex($start = 0)
    {
        $this->initialize();

        if (! $start) {
            // $this->migrateStaff();
            $this->cacheStaff();
        } else {
            $this->cacheStaff();
        }

        $this->migrateCustomers($start);

        echo 'Completed';
    }
}
