<?php

namespace App\Models;

use CodeIgniter\Model;

class OrdersProcessedModel extends Model
{
    // Add the standard Model properties:
    protected $table         = 'orders_processed';
    protected $primaryKey    = 'id';
    protected $allowedFields = [
        'qb_sales_receipt_id',
        'deal_id',
        'retail',
        'cost',
        'gross_profit',
        'createdat',
        'salesman',
        'paid_date',
        // Add any other columns if needed
    ];

    private $logs = [];

    /**
     * Example custom logic your application already uses.
     * We'll keep it here, unchanged, so you do not lose that functionality.
     */
    public function runThirdPass()
    {
        $db = db_connect();
        $this->logs[] = "=== Starting Third Pass for OrdersProcessed (no row limit) ===";

        $iteration = 0;

        while (true) {
            $iteration++;
            $this->logs[] = "=== Iteration #{$iteration} ===";

            // 1) Fetch the next row where:
            //    - o_type=1
            //    - order_processed=0 or NULL
            //    - createdat >= "2024-12-01 00:00:00"
            $rowToProcess = $db->table('bbt_qb_sales_receipts')
                ->where('o_type', '1')
                ->groupStart()
                    ->where('order_processed', '0')
                    ->orWhere('order_processed', null)
                ->groupEnd()
                ->where('createdat >=', '2024-12-01 00:00:00')
                ->orderBy('id', 'ASC')
                ->get(1)
                ->getRowArray();

            if (! $rowToProcess) {
                $this->logs[] = "No more rows found. Stopping.";
                break;
            }

            $qbSalesReceiptId = $rowToProcess['id'];
            $dealId           = $rowToProcess['deal_id'];
            $currentOP        = $rowToProcess['order_processed'] === null ? 'NULL' : $rowToProcess['order_processed'];
            $this->logs[] = "Row found => ID={$qbSalesReceiptId}, deal_id={$dealId}, order_processed={$currentOP}";

            // 2) Look up bbt_orders row
            $sourceOrderRow = $db->table('bbt_orders')
                ->where('id', $dealId)
                ->get()
                ->getRowArray();

            // If missing, set order_processed=2 and continue
            if (! $sourceOrderRow) {
                $this->logs[] = "No bbt_orders row for deal_id={$dealId}. Setting order_processed=2.";
                $db->table('bbt_qb_sales_receipts')
                    ->where('id', $qbSalesReceiptId)
                    ->update(['order_processed' => 2]);
                continue;
            }

            $userID = $sourceOrderRow['createdby'] ?? 0;
            $this->logs[] = "Found bbt_orders => ID={$dealId}, createdby={$userID}";

            // 3) Decode JSON
            $jsonBlob    = $rowToProcess['sales_data'];
            $decodedData = json_decode($jsonBlob, true);

            if (! $decodedData) {
                $this->logs[] = "ERROR: JSON parse fail for qb_sales_receipt ID={$qbSalesReceiptId}. order_processed=2.";
                $db->table('bbt_qb_sales_receipts')
                    ->where('id', $qbSalesReceiptId)
                    ->update(['order_processed' => 2]);
                continue;
            }

            $this->logs[] = "Decoded JSON => " . json_encode($decodedData);

            // 4) Locate all p_o_part items
            $poPartItems = [];
            foreach ($decodedData as $item) {
                if (isset($item['name']) && $item['name'] === 'p_o_part') {
                    $poPartItems[] = $item;
                }
            }
            $this->logs[] = "Found " . count($poPartItems) . " p_o_part items.";

            if (count($poPartItems) === 0) {
                $this->logs[] = "No p_o_part => Setting order_processed=1 for ID={$qbSalesReceiptId}. Skipping.";
                $db->table('bbt_qb_sales_receipts')
                    ->where('id', $qbSalesReceiptId)
                    ->update(['order_processed' => 1]);
                continue;
            }

            // 5) Sum up retail/cost
            $totalRetail = 0.0;
            $totalCost   = 0.0;
            foreach ($poPartItems as $part) {
                $qty    = (float) ($part['qty']    ?? 0);
                $rate   = (float) ($part['rate']   ?? 0);
                $a_cost = (float) ($part['a_cost'] ?? 0);

                $totalRetail += ($qty * $rate);
                $totalCost   += ($qty * $a_cost);
            }
            $totalRetail = round($totalRetail, 2);
            $totalCost   = round($totalCost, 2);
            $grossProfit = round($totalRetail - $totalCost, 2);

            $this->logs[] = "Totals => retail={$totalRetail}, cost={$totalCost}, grossProfit={$grossProfit}";

            // 6) Insert into orders_processed
            $insertData = [
                'qb_sales_receipt_id' => $qbSalesReceiptId,
                'deal_id'             => $dealId,
                'retail'              => $totalRetail,
                'cost'                => $totalCost,
                'gross_profit'        => $grossProfit,
                'createdat'           => $rowToProcess['createdat'],
                'salesman'            => $userID,
                'paid_date'           => null,
            ];
            $this->logs[] = "Inserting => " . json_encode($insertData);

            $db->table('orders_processed')->insert($insertData);
            $newID = $db->insertID();
            $this->logs[] = "Insert success, new orders_processed ID={$newID}.";

            // 7) Mark bbt_qb_sales_receipts => order_processed=1
            $this->logs[] = "Updating bbt_qb_sales_receipts ID={$qbSalesReceiptId} => order_processed=1";
            $db->table('bbt_qb_sales_receipts')
                ->where('id', $qbSalesReceiptId)
                ->update(['order_processed' => 1]);
        }

        $this->logs[] = "=== Finished Third Pass for OrdersProcessed ===";
        $this->finalizeLogs();

        return "Third pass complete for all rows.";
    }

    private function finalizeLogs()
    {
        echo implode("\n", $this->logs) . "\n";
    }
}
