<?php

use BB\Entities\Payment;
use BB\Entities\User;
$I = new UnitTester($scenario);
$I->wantTo('confirm the payment helper fetches the correct payment date');
//Create a user record
$user = User::create(['given_name' => 'Test', 'family_name' => 'Person', 'email' => '*****@*****.**']);
$date = \BB\Helpers\MembershipPayments::lastUserPaymentDate($user->id);
$I->assertFalse($date, 'Date should be false as no payments exist');
//Create some payment records
\BB\Entities\SubscriptionCharge::create(['user_id' => $user->id, 'charge_date' => '2014-01-01', 'payment_date' => '2014-01-01', 'status' => 'paid']);
Payment::create(['reason' => 'subscription', 'source' => 'other', 'user_id' => $user->id, 'amount' => 20, 'amount_minus_fee' => 20, 'status' => 'paid', 'created_at' => '2014-01-01']);
\BB\Entities\SubscriptionCharge::create(['user_id' => $user->id, 'charge_date' => '2014-06-01', 'status' => 'processing']);
Payment::create(['reason' => 'subscription', 'source' => 'other', 'user_id' => $user->id, 'amount' => 20, 'amount_minus_fee' => 20, 'status' => 'pending', 'created_at' => '2014-06-01']);
\BB\Entities\SubscriptionCharge::create(['user_id' => $user->id, 'charge_date' => '2014-08-01', 'status' => 'cancelled']);
Payment::create(['reason' => 'subscription', 'source' => 'other', 'user_id' => $user->id, 'amount' => 20, 'amount_minus_fee' => 20, 'status' => 'cancelled', 'created_at' => '2014-08-01']);
//Now we have some payments re-fetch the last payment date
$date = \BB\Helpers\MembershipPayments::lastUserPaymentDate($user->id);
//Make sure its a date that's returned
$I->assertEquals(get_parent_class($date), 'DateTime');
//Confirm the datetime matched the first payment record, the only paid one
$I->assertEquals(new \Carbon\Carbon('2014-01-01'), $date);
 /**
  * The bill has been cancelled or failed, update the user records to compensate
  *
  * @param $existingPayment
  */
 private function handleFailedCancelledBill(Payment $existingPayment)
 {
     if ($existingPayment->reason == 'subscription') {
         //If the payment is a subscription payment then we need to take action and warn the user
         $user = $existingPayment->user()->first();
         $user->status = 'suspended';
         //Rollback the users subscription expiry date or set it to today
         $expiryDate = \BB\Helpers\MembershipPayments::lastUserPaymentExpires($user->id);
         if ($expiryDate) {
             $user->subscription_expires = $expiryDate;
         } else {
             $user->subscription_expires = new Carbon();
         }
         $user->save();
         //Update the subscription charge to reflect the payment failure
         $subCharge = $this->subscriptionChargeRepository->getById($existingPayment->reference);
         if ($subCharge) {
             $this->subscriptionChargeRepository->paymentFailed($subCharge->id);
         }
     } elseif ($existingPayment->reason == 'induction') {
         //We still need to collect the payment from the user
     } elseif ($existingPayment->reason == 'box-deposit') {
     } elseif ($existingPayment->reason == 'key-deposit') {
     }
 }
 /**
  * Fetch a payment record using the id provided by the payment provider
  *
  * @param $sourceId
  * @return Payment
  */
 public function getPaymentBySourceId($sourceId)
 {
     return $this->model->where('source_id', $sourceId)->first();
 }
 /**
  * Store a newly created resource in storage.
  *
  * @return Response
  */
 public function store()
 {
     $spreadsheetPath = \Input::file('statement')->getRealPath();
     $testProcess = \Request::get('test');
     if ($testProcess) {
         $testProcess = true;
         echo "Test Mode - no payment records are being created<br /><br />";
     } else {
         $testProcess = false;
         echo "Live Mode - Payments have been created<br /><br />";
     }
     $reader = new SpreadsheetReader($spreadsheetPath);
     $reader->ChangeSheet(0);
     $stringMatchUsers = User::active()->where('import_match_string', '!=', '')->get();
     $users = User::active()->get();
     echo '<br />' . PHP_EOL;
     echo '<table width="100%">';
     foreach ($reader as $i => $row) {
         echo "<tr>";
         $subPayment = false;
         $balancePayment = false;
         $paymentReference = null;
         //print_r($row);
         //If the payment isn't a credit then we don't care about it
         //if (($row[1] != 'CR') && ($row[1]) != 'BP')
         if ($row[1] != 'CR') {
             continue;
         }
         if (strpos(strtoupper($row[2]), 'GC C1 BUILDBRIGHTO') !== false) {
             continue;
         }
         if (strpos(strtoupper($row[2]), 'STRIPE TRANSFER') !== false) {
             continue;
         }
         if (strpos(strtoupper($row[2]), 'EVENTBRITE') !== false) {
             continue;
         }
         $date = new \Carbon\Carbon($row[0]);
         echo "<td>" . $date->format('d/m/y') . '</td>';
         //echo "<td>".$row[1].'</td>';
         if (strpos(strtoupper($row[2]), 'SUB') !== false) {
             $subPayment = true;
         } elseif (strpos($row[2], 'MEMBERSHIP') !== false) {
             $subPayment = true;
         } elseif (strpos($row[2], '-BALANCE-') !== false) {
             $balancePayment = true;
             $descriptionParts = explode('-BALANCE-', $row[2]);
             if (is_array($descriptionParts) && count($descriptionParts) > 1) {
                 $paymentReference = strtolower($descriptionParts[1]);
             }
         }
         if ($subPayment) {
             echo '<td>SUB</td>';
             $reasonString = 'subscription';
         } elseif ($balancePayment) {
             echo '<td>Balance</td>';
             $reasonString = 'balance';
         } else {
             echo '<td></td>';
             $reasonString = 'unknown';
         }
         $matchedUser = false;
         $paymentDescription = strtolower($row[2]);
         //Try matching against specific match strings first
         foreach ($stringMatchUsers as $user) {
             if (strpos($paymentDescription, strtolower($user->import_match_string)) !== false) {
                 $matchedUser = $user;
                 break;
             }
         }
         //If there was no match do a general surname match
         if (!$matchedUser) {
             foreach ($users as $user) {
                 if (strpos($paymentDescription, strtolower($user->family_name)) !== false) {
                     $matchedUser = $user;
                     break;
                 }
             }
         }
         if ($matchedUser) {
             echo '<td>' . $matchedUser->name . '</td>';
             if ($subPayment) {
                 $subCharge = $this->subscriptionChargeRepository->findCharge($matchedUser->id, $date);
                 if ($subCharge) {
                     echo '<td>Subscription Payment</td>';
                 } else {
                     echo '<td style="background-color: #ff8c14;">Unknown: Recording as balance top up</td>';
                     $subPayment = false;
                     $reasonString = 'balance';
                 }
             }
         } else {
             echo '<td style="background-color: #F00;">Unknown</td><td></td>';
         }
         echo '<td>' . $row[2] . '</td>';
         //echo '<td>'.$row[3].'</td>';
         echo '<td>' . $row[4] . '</td>';
         echo "</tr>";
         if (!$testProcess && $matchedUser) {
             if ($subPayment) {
                 if (isset($subCharge) && $subCharge) {
                     $paymentReference = $subCharge->id;
                     $this->subscriptionChargeRepository->markChargeAsPaid($subCharge->id, $date, $row[4]);
                 }
             }
             Payment::create(['created_at' => $date, 'reason' => $reasonString, 'source' => 'standing-order', 'user_id' => $matchedUser->id, 'amount' => $row[4], 'fee' => 0, 'amount_minus_fee' => $row[4], 'status' => 'paid', 'reference' => $paymentReference]);
             if ($subPayment) {
                 if ($matchedUser->payment_method == 'standing-order') {
                     $matchedUser->monthly_subscription = $row[4];
                 }
                 $matchedUser->save();
             }
         }
     }
     echo "</table>";
     exit;
 }