<?php

namespace Velis\Xls;

use XLSXWriter;
use XLSXWriter_BuffererWriter;

/**
 * Lite XLSX Writer
 *
 * @author Olek Procki <olo@velistech.com>
 */
class XlsxWriterLite extends XLSXWriter
{
    const COLUMN_TYPE_NUMERIC = '0.00';
    const COLUMN_TYPE_DATE = 'date';
    const COLUMN_TYPE_DATETIME = 'datetime';

    /**
     * @param  string $date_input
     * @return string
     */
    public static function convertDateTime($date_input)
    {
        $value = parent::convert_date_time($date_input);
        return str_replace(',', '.', (string)$value);
    }

    protected function writeCell(XLSXWriter_BuffererWriter &$file, $row_number, $column_number, $value, $num_format_type, $cell_style_idx)
    {
        $cell_name = self::xlsCell($row_number, $column_number);

        if (!is_scalar($value) || $value === '') { //objects, array, empty
            $file->write('<c r="' . $cell_name . '" s="' . $cell_style_idx . '"/>');
        } elseif (is_string($value) && $value[0] == '=') {
            $file->write('<c r="' . $cell_name . '" s="' . $cell_style_idx . '" t="s"><f>' . self::xmlspecialchars(ltrim($value, '=')) . '</f></c>');
        } elseif ($num_format_type == 'n_date') {
            $file->write('<c r="' . $cell_name . '" s="' . $cell_style_idx . '" t="n"><v>' . intval(self::convertDateTime($value)) . '</v></c>');
        } elseif ($num_format_type == 'n_datetime') {
            $file->write('<c r="' . $cell_name . '" s="' . $cell_style_idx . '" t="n"><v>' . self::convertDateTime($value) . '</v></c>');
        } elseif ($num_format_type == 'n_numeric') {
            $file->write('<c r="' . $cell_name . '" s="' . $cell_style_idx . '" t="n"><v>' . self::xmlspecialchars($value) . '</v></c>');//int,float,currency
        } elseif ($num_format_type == 'n_string') {
            $file->write('<c r="' . $cell_name . '" s="' . $cell_style_idx . '" t="inlineStr"><is><t>' . self::xmlspecialchars($value) . '</t></is></c>');
        } elseif ($num_format_type == 'n_auto' || 1) { //auto-detect unknown column types
            if (!is_string($value) || $value == '0' || ($value[0] != '0' && ctype_digit($value)) || preg_match("/^\-?(0|[1-9][0-9]*)(\.[0-9]+)?$/", $value)) {
                $file->write('<c r="' . $cell_name . '" s="' . $cell_style_idx . '" t="n"><v>' . self::xmlspecialchars($value) . '</v></c>');//int,float,currency
            } else { //implied: ($cell_format=='string')
                $file->write('<c r="' . $cell_name . '" s="' . $cell_style_idx . '" t="inlineStr"><is><t>' . self::xmlspecialchars($value) . '</t></is></c>');
            }
        }
    }
}
