<?php

namespace App\Traits;
# Models
use App\Models\User;
use App\Models\Wallet;
use App\Models\Period;
use App\Models\WalletHistory;
use App\Models\GamePlayTime;
use App\Models\NumberBetting;
use App\Models\PaymentHistory;
use App\Models\RouletteBettings;
use Kreait\Firebase\Factory;
use Kreait\Firebase\Exception\FirebaseException;
use Illuminate\Support\Facades\Auth;

trait MasterTraits
{

  function walletss($gameId, $userId, $period_id, $amount, $amountType, $comment)
  {
    if ($gameId == 1) {
      $checkWallet = NumberBetting::firstOrCreate(['user_id' => $userId, 'period_id' => $period_id]);
      // Update wallet based on the type of transaction
      switch ($amountType) {
        case 'Profit':
          $checkWallet->profit += $amount;
          $checkWallet->result = 'win';
          PaymentRemark($userId, $comment, $amount);
          break;

        case 'Loss':
          $checkWallet->loss += $amount;
          $checkWallet->result = 'loss';
          break;

        default:
          // Handle unexpected $amountType values
          throw new \Exception('Invalid amount type');
      }

      // Save the updated wallet information
      $checkWallet->save();
    } elseif ($gameId == 2) {
      $checkWallet = RouletteBettings::firstOrCreate(['id' => $period_id]);
      // Update wallet based on the type of transaction
      switch ($amountType) {
        case 'Profit':
          $checkWallet->profit += $amount;
          $checkWallet->result = 'win';
          PaymentRemark($userId, $comment, $amount);
          break;

        case 'Loss':
          $checkWallet->loss += $amount;
          $checkWallet->result = 'loss';
          break;

        default:
          // Handle unexpected $amountType values
          throw new \Exception('Invalid amount type');
      }

      // Save the updated wallet information
      $checkWallet->save();
    }

    // return true;
  }
  function periodcreate($game_id, $play_time_id)
  {
    // Get last period for this game & play_time
    $lastPeriod = Period::where('play_time_id', $play_time_id)
      ->where('game_id', $game_id)
      ->orderBy('id', 'DESC')
      ->first();

    // Build prefix: current year + day + month
    $currentYear = date('Y');   // 2025
    $day         = date('d');   // 30
    $month       = date('m');   // 09

    $prefix = $currentYear . $day . $month;
    // → 20253009

    // Default start sequence
    $sequence = 1;

    if ($lastPeriod && str_starts_with($lastPeriod->period, $prefix)) {
      // Extract last sequence
      $lastSeq = (int)substr($lastPeriod->period, -4);
      $sequence = $lastSeq + 1;
    }

    // Pad sequence to 6 digits
    $periodId = $prefix . str_pad($sequence, 4, '0', STR_PAD_LEFT);

    // Save period
    $data = [
      'play_time_id' => $play_time_id,
      'game_id'      => $game_id,
      'period'       => $periodId,
    ];

    return Period::create($data);
  }


  // function periodcreate($game_id, $play_time_id)
  // {

  //   $lastPeriod = Period::where('play_time_id', $play_time_id)
  //     ->where('game_id', $game_id)
  //     ->orderBy('id', 'DESC')
  //     ->first();

  //   // Default to a 12-digit starting period.
  //   $defaultLength = 12;
  //   $periodId = str_pad('1', $defaultLength, '0', STR_PAD_LEFT);

  //   if ($lastPeriod) {
  //     // Get the current period length or fallback to the default length.
  //     $currentLength = max(strlen($lastPeriod->period), $defaultLength);

  //     // Increment the period and pad dynamically to match the new length.
  //     $periodId = str_pad((int)$lastPeriod->period + 1, $currentLength, '0', STR_PAD_LEFT);
  //   }

  //   $data = [
  //     'play_time_id' => $play_time_id,
  //     'game_id'      => $game_id,
  //     'period'       => $periodId,
  //   ];

  //   $success = Period::create($data);
  //   // $checkPlayTime = GamePlayTime::whereId($play_time_id)->first();
  //   // $factory = (new Factory)->withServiceAccount(base_path('storage/app/firebase_credentials.json'));

  //   // // Create Firestore database instance
  //   // $firestore = $factory->createFirestore();
  //   // $database = $firestore->database();
  //   // // Choose the collection and document dynamically
  //   // $collectionName = $game_id == 1 ? 'ColorPrediction' : 'Roullet';
  //   // $documentName = $game_id == 1 ? $checkPlayTime->time . 's' : 'roullet60s';
  //   // $collection = $database->collection($collectionName);
  //   // $document = $collection->document($documentName);
  //   // // Set data
  //   // $document->update([
  //   //   ['path' =>  'period', 'value' => $success->period],
  //   // ]);
  //   return $success;
  // }
  function resultcreate($result, $gameid, $play_time_id)
  {
    $factory = (new Factory)->withServiceAccount(base_path('storage/app/firebase_credentials.json'));

    // Create Firestore database instance
    $firestore = $factory->createFirestore();
    $database = $firestore->database();

    $checkPlayTime = GamePlayTime::whereId($play_time_id)->first();

    $collectionName = $gameid == 1 ? 'ColorPrediction' : 'Roullet';
    $documentName = $gameid == 1 ? $checkPlayTime->time . 's' : 'roullet60s';

    // Specify collection and document
    $collection = $database->collection($collectionName);
    $document = $collection->document($documentName); // Use a unique ID

    // Set data
    $document->update([
      ['path' => 'result', 'value' => $result]
    ]);
  }
}
