<?php
/*******************************************************************************

    Copyright 2012 Whole Foods Co-op

    This file is part of IT CORE.

    IT CORE is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    IT CORE is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    in the file license.txt along with IT CORE; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

*********************************************************************************/

namespace COREPOS\pos\plugins\Paycards\sql;
use COREPOS\pos\lib\Database;
use \Exception;

class PaycardVoidRequest extends PaycardRequest
{
    public function __construct($refnum, $dbTrans)
    {
        parent::__construct($refnum, $dbTrans);
        $original = $this->conf->get('paycard_trans');
        $this->original = explode('-', $original);
    }

    public function saveRequest()
    {
        /**
          populate a void record in PaycardTransactions
        */
        $orig = $this->findOriginal();
        $initQ = $this->dbTrans->prepare("INSERT INTO PaycardTransactions (
                    dateID, empNo, registerNo, transNo, transID,
                    previousPaycardTransactionID, processor, refNum,
                    live, cardType, transType, amount, PAN, issuer,
                    name, manual, requestDateTime)
                VALUES (?, ?, ?, ?, ?,
                    ?, ?, ?,
                    ?, ?, ?, ?, ?, ?,
                    ?, ?, ?)");
        $args = array(
            $orig['dateID'], $orig['empNo'], $orig['registerNo'], $orig['transNo'], $orig['transID'],
            $orig['previousPaycardTransactionID'], $orig['processor'], $orig['refNum'],
            $orig['live'], $orig['cardType'], 'VOID', $orig['amount'], $orig['PAN'], $orig['issuer'],
            $orig['name'], $orig['manual'], $orig['requestDateTime']);
        $initR = $this->dbTrans->execute($initQ, $args);
        if ($initR === false) {
            $log = new \COREPOS\pos\lib\LaneLogger();
            $log->debug("SQL error: " . $this->dbTrans->error());
            throw new Exception('Error saving void request in PaycardTransactions');
        }
        $this->last_paycard_transaction_id = $this->dbTrans->insertID();
    }

    public function findOriginal()
    {
        $sql = 'SELECT refNum,
                    xTransactionID,
                    amount,
                    xToken as token,
                    xProcessorRef as processData,
                    xAcquirerRef AS acqRefData,
                    xApprovalNumber,
                    transType AS mode,
                    manual,
                    cardType,
                    dateID, empNo, registerNo, transNo, transID,
                    previousPaycardTransactionID, processor,
                    live, amount, PAN, issuer,
                    name, requestDateTime
                FROM PaycardTransactions
                WHERE dateID=' . $this->today . '
                    AND empNo=' . $this->cashierNo . '
                    AND registerNo=' . $this->original[1] . '
                    AND transNo=' . $this->original[2] . '
                    AND transID=' . $this->transID;
        $res = $this->dbTrans->query($sql);
        if ($res === false || $this->dbTrans->numRows($res) != 1) {
            $server = Database::mDataConnect();
            $res2 = $server->query($sql);
            $log = new \COREPOS\pos\lib\LaneLogger();
            //$log->debug($sql);
            if ($res2 === false || $server->numRows($res2) != 1) {
                throw new Exception('Could not locate original transaction');
            }
            return $server->fetchRow($res2);
        }

        return $this->dbTrans->fetchRow($res);
    }

    /**
      On an unsuccessful void attempt zero out the transID field

      Normally the PaycardTransactions record for the original transaction and the
      reversal have the same transID. This prevents "re-voiding" a transaction (the
      processor should, too, but better safe than sorry). If the void attempt fails
      zeroing this record out allows for another attempt
    */
    public function dropTransID()
    {
        $prep = $this->dbTrans->prepare('UPDATE PaycardTransactions SET transID=0 WHERE paycardTransactionID=?');
        $this->dbTrans->execute($prep, array($this->last_paycard_transaction_id));
    }
}

