<?php
session_start();
include_once( dirname(dirname(__FILE__)) . '/../classes/check.class.php');
include_once __DIR__ . '/../classes/functions.php';
protect('*');

$input = filter_var_array( $_POST, FILTER_SANITIZE_STRING );

$ajaxEstimation = new AjaxEstimation();

switch ( $input['action'] )
{
    default:
        $ajaxEstimation->{$input['action']}($input);
        break;
}

/**
 * Class AjaxEstimation
 *
 * @property PDO $pdo
 * @property DB $db
 */
class AjaxEstimation {

    protected $db;
    protected $pdo;

    public function __construct()
    {
        $this->db = DB::getInstance();
        $this->pdo = $this->db->dbh;
    }

    public function createInvoice() {}

    public function createEstimation() {}

    public function createReclamation() {}

    public function loadAllReclamations($request)
    {
        $data = $this->db->query('SELECT DISTINCT r.*, c.fname, c.lname, c.address, c.tel1 FROM reclamation r INNER JOIN clients c ON c.clientid = r.client_id')->toArray();
        $this->response( $data );
    }

    public function getAppointmentPhotos($request)
    {
        $data = $this->db->query('select * from appointment_photo where token = ?', [ $request['data']['token'] ])->toArray();
        $this->response( $data );
    }

    public function deleteReclamationPhoto($request)
    {
        $this->response( $this->db->delete('appointment_photo', $request['data']['id']) );
    }

    public function uploadReclamationPhoto($request)
    {
        if ( !empty($_FILES) ) {
            $destination_folder = 'assets/uploads/';
            $temp_file = $_FILES['file']['tmp_name'];
            $image_size_data = getimagesize($temp_file);
            if( $image_size_data ){
                $file_name = explode(".",$_FILES["file"]["name"]);
                $extension = $file_name[1];
                $new_name = $file_name[0].'_'.round(microtime(true) * 1000);
                $new_file_name = $new_name .".".$extension;
                $target_file =  __DIR__ .'/../../assets/uploads/'. $new_file_name;
                $result = move_uploaded_file($temp_file,$target_file);
                if ($result) {
                    $data = array(
                        'token' => $request['data']['token'],
                        'photo_url' => $destination_folder. $new_file_name,
                        'appointment_id' => 0,
                    );
                    addAppointmentPhoto($data);
                }
            }
        }

        $this->getAppointmentPhotos($request);
    }

    public function CheckAndFetchRecentlyCreatedReclamationBySession($request)
    {
        $session_id = session_id();
        if ( $session_id ) {
            $data = $this->db->query('SELECT r.*, c.fname, c.lname, c.address, c.tel1 FROM reclamation r
                LEFT JOIN clients c ON c.clientid = r.client_id
WHERE r.session_id = ? ORDER BY id DESC LIMIT 1', [ $session_id ])->toArray();

            if ( isset($data[0]) && !empty($data[0]) ) {
                $this->db->update('reclamation', [
                    'session_id' => 0,
                ], $data[0]['id']);
                $this->response($data[0]);
            }

            $this->response( $data );
        }

        $this->response([]);
    }

    public function createEstimateAndInvoice($request)
    {
        $this->pdo->beginTransaction();
        try {
            $estimation = $request['estimation'];
            $invoice    = $request['invoice'];
            $reclamation = $estimation['reclamation'];
            $client = getClient($reclamation['client_id']);
            //create invoice
            $invoiceData = [
                'client_id' => $reclamation['client_id'],
                'date' => date('Y-m-d', strtotime($estimation['time_of_loss'])),
                'reclamation' => $reclamation['reclamation'],
                'f_name' => $client['f_name'],
                'l_name' => $client['l_name'],
                'tel' => $client['tel'],
                'email' => $client['email'],
                'company' => $client['company'],
                'vin' => $reclamation['vin'],
                'brand' => $reclamation['brand'],
                'model' => $reclamation['model'],
                'year' => $reclamation['year'],
                'inventory' => $reclamation['inventory'],
                'color' => $reclamation['color'],
                'millage' => number_format(floatval($reclamation['millage']), 2),
                'rental_agreement' => $invoice['rental_agreement'],
                'rental_car' => $invoice['rental_car'],
                'number_of_days' => $invoice['number_of_days'],
                'payment_status' => $invoice['payment_status'],
                'payment_method' => $invoice['payment_method'],
                'signature' => $invoice['signature'],
                'signature_img' => $invoice['signature_img'],
                'created_by' => $_SESSION['jigowatt']['user_id'],
                'invoice_type' => 'estimate'
            ];

            $invElements = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,'stripping','other_fees','glazier','work_force','parts'];
            foreach ( $invElements as $invElement ) {
                $invoiceData['inv_' . $invElement . '_tech']    = $invoice['inv_' . $invElement . '_tech'];
                $invoiceData['inv_' . $invElement . '_note']    = $invoice['inv_' . $invElement . '_note'];
                $invoiceData['inv_' . $invElement . '_price']   = $invoice['inv_' . $invElement . '_price'];
            }
            $invoiceData['sub_total'] = $invoice['sub_total'];
            $invoiceData['tps'] = $invoice['tps'];
            $invoiceData['tvq'] = $invoice['tvq'];
            $invoiceData['franchise'] = $invoice['franchise'];
            $invoiceData['total'] = $invoice['total'];
            $invoiceData['deposit'] = $invoice['deposit'];
            $invoiceData['balance'] = $invoice['balance'];
            $invoiceData['damages'] = $invoice['damages'];

            if ( count($invoice['parts']) > 0 ) {
                //$invoiceData['inv_parts_note'] = count($invoice['parts']) . ' part' . (count($invoice['parts']) > 1 ? 's' : '');
            }

            if ( !empty($invoiceData['reclamation']) && !empty($invoiceData['client_id']) ) {
                $invoiceData['confirm_invoice'] = 1;
            }

            $invoiceId = $this->db->insert('invoice', $invoiceData);

            foreach ( $reclamation['photos'] as $photo ) {
                $this->db->insert('invoice_photo', [
                    'invoice_id' => $invoiceId,
                    'photo_url'  => $photo['photo_url'],
                ]);
            }

            //add parts
            if ( !empty($invoice['parts']) ) {
                foreach ( $invoice['parts'] as $part ) {
                    $part['invoice_id'] = $invoiceId;
                    $this->db->insert('parts', $part);
                }
            }

            //create estimation
            $this->db->insert('estimations', [
                'reclamation_id' => $reclamation['id'],
                'invoice_id' => $invoiceId,
                'time_of_loss' => date('Y-m-d', strtotime($estimation['time_of_loss'])),
                'franchise' => $estimation['franchise'],
                'created_by' => $_SESSION['jigowatt']['user_id'],
                'estimator_id' => $_SESSION['jigowatt']['user_id'],
                'address' => $estimation['address'],
                'tel' => $estimation['tel'],
                'type_of_loss' => $estimation['type_of_loss'],
                'fax' => $estimation['fax'],
                'client_id' => $reclamation['client_id'],
                'claim_collector' => $estimation['claim_collector'],
            ]);

            $this->pdo->commit();

            $this->response( ['message' => 'Successfully stored!'] );

        } catch (Exception $exception) {
            $this->pdo->rollBack();
            throw new Exception($exception->getMessage());
        }
    }

    public function updateEstimateAndInvoice($request)
    {
        $this->pdo->beginTransaction();
        try {
            $estimation = $request['estimation'];
            $invoice    = $request['invoice'];
            $reclamation = $estimation['reclamation'];
            $client = getClient($reclamation['client_id']);
            //create invoice
            $invoiceData = [
                'client_id' => $reclamation['client_id'],
                'date' => date('Y-m-d', strtotime($estimation['time_of_loss'])),
                'reclamation' => $reclamation['reclamation'],
                'f_name' => $client['f_name'],
                'l_name' => $client['l_name'],
                'tel' => $client['tel'],
                'email' => $client['email'],
                'company' => $client['company'],
                'vin' => $reclamation['vin'],
                'brand' => $reclamation['brand'],
                'model' => $reclamation['model'],
                'year' => $reclamation['year'],
                'inventory' => $reclamation['inventory'],
                'color' => $reclamation['color'],
                'millage' => number_format(floatval($reclamation['millage']), 2),
                'rental_agreement' => $invoice['rental_agreement'],
                'rental_car' => $invoice['rental_car'],
                'number_of_days' => $invoice['number_of_days'],
                'payment_status' => $invoice['payment_status'],
                'payment_method' => $invoice['payment_method'],
                'created_by' => $_SESSION['jigowatt']['user_id'],
            ];

            if ( !empty($invoice['signature']) ) {
                $invoiceData['signature'] = $invoice['signature'];
            }
            if ( !empty($invoice['signature_img']) ) {
                $invoiceData['signature_img'] = $invoice['signature_img'];
            }

            $invElements = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,'stripping','other_fees','glazier','work_force','parts'];
            foreach ( $invElements as $invElement ) {
                $invoiceData['inv_' . $invElement . '_tech']    = $invoice['inv_' . $invElement . '_tech'];
                $invoiceData['inv_' . $invElement . '_note']    = $invoice['inv_' . $invElement . '_note'];
                $invoiceData['inv_' . $invElement . '_price']   = $invoice['inv_' . $invElement . '_price'];
            }
            $invoiceData['sub_total'] = $invoice['sub_total'];
            $invoiceData['tps'] = $invoice['tps'];
            $invoiceData['tvq'] = $invoice['tvq'];
            $invoiceData['franchise'] = $invoice['franchise'];
            $invoiceData['total'] = $invoice['total'];
            $invoiceData['deposit'] = $invoice['deposit'];
            $invoiceData['balance'] = $invoice['balance'];
            $invoiceData['damages'] = $invoice['damages'];

            if ( count($invoice['parts']) > 0 ) {
                //$invoiceData['inv_parts_note'] = count($invoice['parts']) . ' part' . (count($invoice['parts']) > 1 ? 's' : '');
            }

            $invoiceId = $invoice['id'];

            $this->db->update('invoice', $invoiceData, $invoiceId);

//            foreach ( $reclamation['photos'] as $photo ) {
//                $this->db->insert('invoice_photo', [
//                    'invoice_id' => $invoiceId,
//                    'photo_url'  => $photo['photo_url'],
//                ]);
//            }

            //add parts
            if ( !empty($invoice['parts']) ) {
                $this->db->query('DELETE FROM parts WHERE invoice_id = ?', [ $invoiceId ]);
                foreach ( $invoice['parts'] as $part ) {
                    $part['invoice_id'] = $invoiceId;
                    $this->db->insert('parts', $part);
                }
            }

            //create estimation
            $this->db->update('estimations', [
                'reclamation_id' => $reclamation['id'],
                'invoice_id' => $invoiceId,
                'time_of_loss' => date('Y-m-d', strtotime($estimation['time_of_loss'])),
                'franchise' => $estimation['franchise'],
                'created_by' => $_SESSION['jigowatt']['user_id'],
                'estimator_id' => $_SESSION['jigowatt']['user_id'],
                'address' => $estimation['address'],
                'tel' => $estimation['tel'],
                'type_of_loss' => $estimation['type_of_loss'],
                'fax' => $estimation['fax'],
                'client_id' => $reclamation['client_id'],
                'claim_collector' => $estimation['claim_collector'],
            ], $estimation['id']);

            $this->pdo->commit();

            $this->response( ['message' => 'Successfully stored!'] );

        } catch (Exception $exception) {
            $this->pdo->rollBack();
            throw new Exception($exception->getMessage());
        }
    }

    public function changeInvoiceType($request)
    {
        $invoice    = $request['invoice'];
        $this->db->query('UPDATE invoice SET invoice_type = ? WHERE id = ?', ['invoice', $invoice['id']]);

        $this->response( [ 'message' => $invoice ], 200 );
    }

    public function loadContentById($request)
    {

        $id = (int) $request['id'];

        if ( is_numeric( $id ) ) {
            $estimation = $this->db->query('SELECT e.*, r.reclamation FROM estimations e INNER JOIN reclamation r ON r.id = e.reclamation_id WHERE e.id = ?', [$request['id']])->toArray();
            if ( !empty($estimation[0]) ) {
                $estimation = $estimation[0];
                $invoice = $this->db->query( 'SELECT * FROM invoice WHERE id = ? ORDER BY id DESC LIMIT 1', [ $estimation['invoice_id'] ] )->first();
                $reclamation = $this->db->query('SELECT r.*, c.fname, c.lname, c.address, c.tel1 FROM reclamation r
                  LEFT JOIN clients c ON c.clientid = r.client_id WHERE r.reclamation = ? LIMIT 1', [ $estimation['reclamation'] ])->first();
                $estimationPhotos = $this->db->query('SELECT * FROM appointment_photo WHERE token = ?', [ $reclamation->token ])->toArray();
                $parts = $this->db->query('SELECT * FROM parts WHERE invoice_id = ?', [$invoice->id])->toArray();
                if ( $invoice ) {
                    $invoice->parts = $parts;
                }

                $this->response([
                    'estimation' => $estimation,
                    'invoice'    => $invoice,
                    'reclamation' => $reclamation,
                    'reclamationPhotos' => $estimationPhotos
                ]);
            }
        }

        $this->response( [ 'message' => 'Please provide a valid estimation ID' ], 404 );
    }

    private function response( $data, $code = 200 )
    {
        http_response_code($code);
        echo json_encode( $data );
        exit;
    }
}
