<?php
class ProductPage extends Page {
    private $action = 'list';
    private $product = null;

    public function __construct() {
        parent::__construct();
        if(isset($_GET['action'])) {
            $this->action = $_GET['action'];
        }
        if(isset($_GET['id'])) {
            $id = $_GET['id'];
            if($id) {
                try {
                    $this->product = new Product($id);
                } catch(Exception $e) {
                    $this->action = 'list';
                    $this->product = null;
                    $this->error = i18n('There is no product with that ID.');
                }
            }
        }
        switch($this->action) {
            case 'show':
                $this->subtitle = i18n('Product details');
                break;
            case 'list':
                $this->subtitle = i18n('Product list');
                break;
        }
    }

    protected function render_body() {
        switch($this->action) {
            case 'list':
                $products = $this->build_product_table(get_items('product'));
                print(replace(array('product_table' => $products),
                              $this->fragments['product_page']));
                break;
            case 'show':
                print($this->build_product_form());
                break;
        }
    }

    private function build_product_form() {
        $discarded = $this->product->get_discardtime();

        $info_item_fragment = $this->fragments['info_item'];
        $tag_fragment = $this->fragments['tag'];
        $product_details_fragment = $this->fragments['product_details'];
        if($discarded) {
            $info_item_fragment = $this->fragments['info_item_readonly'];
            $tag_fragment = $this->fragments['tag_readonly'];
            $product_details_fragment = $this->fragments['product_details_readonly'];
        }
        $info = '';
        foreach($this->product->get_info() as $key => $value) {
            $name = ucfirst(str_replace('_', ' ', $key));
            $info .= replace(array('name' => $name,
                                   'key' => $key,
                                   'value' => $value),
                             $info_item_fragment);
        }
        $tags = '';
        foreach($this->escape_tags($this->product->get_tags()) as $tag) {
            $tags .= replace(array('tag' => ucfirst($tag)),
                             $tag_fragment);
        }
        $history = $this->build_history_table($this->product->get_history());
        $attachments = $this->build_attachment_list(
            $this->product->get_attachments());
        $fields = array('id'          => $this->product->get_id(),
                        'brand'       => $this->product->get_brand(),
                        'name'        => $this->product->get_name(),
                        'serial'      => $this->product->get_serial(),
                        'invoice'     => $this->product->get_invoice(),
                        'tags'        => $tags,
                        'info'        => $info,
                        'label'       => '',
                        'label_hidden' => 'hidden',
                        'checkout_hidden'      => 'hidden',
                        'hidden'      => '',
                        'service'     => i18n('Start service'),
                        'history'     => $history,
                        'attachments' => $attachments,
                        'end'         => format_date(default_loan_end(time())));
        if(class_exists('QRcode')) {
            $fields['label'] = replace($fields,
                                       $this->fragments['product_label']);
        }
        if(!$this->product->get_discardtime()) {
            $fields['label_hidden'] = '';
            if($this->product->get_status() == 'service') {
                $fields['service'] = i18n('End service');
            }
            if($this->product->get_status() == 'available') {
                $fields['checkout_hidden'] = '';
            }
        }
        $out = replace($fields, $product_details_fragment);
        $out .= replace($fields, $this->fragments['product_meta']);
        return $out;
    }

    private function build_history_table($history) {
        if(!$history) {
            return i18n('No history to display.');
        }
        $rows = '';
        foreach($history as $event) {
            $status = $event->get_status();
            $itemlink = 'Service';
            $start = $event->get_starttime();
            $end = $event->get_returntime();
            $note = '';
            if($event instanceof Loan) {
                $user = $event->get_user();
                $product = $event->get_product();
                $itemlink = replace(array('id' => $user->get_id(),
                                          'name' => $user->get_name(),
                                          'page' => 'users'),
                                    $this->fragments['item_link']);
                if(!$end) {
                    $end = $event->get_endtime();
                    $extend = format_date(default_loan_end(time()));
                    $note = replace(array('id' => $product->get_id(),
                                          'end_new' => $extend),
                                    $this->fragments['loan_extend_form']);
                }
            }
            $rows .= replace(array('status' => $status,
                                   'name' => $itemlink,
                                   'start_date' => format_date($start),
                                   'end_date' => format_date($end),
                                   'note' => $note),
                             $this->fragments['product_loan_table_row']);
        }
        return replace(array('rows' => $rows),
                       $this->fragments['product_loan_table']);
    }


    private function build_attachment_list($attachments) {
        if(!$attachments) {
            return '<p>'.i18n('No attachments.').'</p>';
        }
        $items = '';
        foreach($attachments as $attachment) {
            $date = format_date($attachment->get_uploadtime());
            $items .= replace(array('name' => $attachment->get_filename(),
                                    'id'   => $attachment->get_id(),
                                    'date' => $date),
                              $this->fragments['attachment']);
        }
        return replace(array('attachments' => $items),
                       $this->fragments['attachment_list']);
    }
}
?>