<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class InvoiceController extends Controller
{
    private function branchFromBearerToken(Request $request): object
    {
        $auth = $request->header('Authorization', '');
        if (!preg_match('/Bearer\s+(.+)/i', $auth, $m)) {
            abort(response()->json(['message' => 'Missing Bearer token'], 401));
        }

        $token = trim($m[1]);

        $branch = DB::table('branches')
            ->where('api_token', $token)
            ->where('is_active', 1)
            ->first();

        if (!$branch) {
            abort(response()->json(['message' => 'Invalid token'], 401));
        }

        return $branch;
    }

    // يحول "2022-03-08 21:13:15.443" إلى "2022-03-08 21:13:15"
    private function normalizeBillDate(?string $billDate): ?string
    {
        if (!$billDate) return null;

        // إذا فيه .milliseconds نقصها
        $pos = strpos($billDate, '.');
        if ($pos !== false) {
            return substr($billDate, 0, $pos);
        }

        return $billDate;
    }

    public function ping(Request $request)
    {
        $branch = $this->branchFromBearerToken($request);

        return response()->json([
            'ok' => true,
            'branch_id' => (int)$branch->id,
            'branch_no' => $branch->branch_no ?? null,
            'name' => $branch->name ?? null,
            'code' => $branch->code ?? null,
        ], 200);
    }

    public function store(Request $request)
    {
        $branch = $this->branchFromBearerToken($request);

        $data = $request->validate([
            'bill_no'       => 'required|string|max:50',
            'bill_date'     => 'required|string', // سننظمه
            'grand_total'   => 'required|numeric',
            'discount_per'  => 'nullable|numeric',
            'payment_mode'  => 'nullable|string|max:50',
            'operator'      => 'nullable|string|max:100',
            'status'        => 'nullable|string|max:20',
        ]);

        $row = [
            'branch_id'     => (int)$branch->id,
            'bill_no'       => $data['bill_no'],
            'bill_date'     => $this->normalizeBillDate($data['bill_date']),
            'grand_total'   => (float)$data['grand_total'],
            'discount_per'  => (float)($data['discount_per'] ?? 0),
            'payment_mode'  => $data['payment_mode'] ?? null,
            'operator'      => $data['operator'] ?? null,
            'status'        => $data['status'] ?? null,
            'created_at'    => now(),
            'updated_at'    => now(),
        ];

        // Upsert حسب (branch_id + bill_no) عشان التكرار ما يسبب مشكلة
        DB::table('sales_invoices')->upsert(
            [$row],
            ['branch_id', 'bill_no'],
            ['bill_date','grand_total','discount_per','payment_mode','operator','status','updated_at']
        );

        return response()->json([
            'ok' => true,
            'branch_id' => (int)$branch->id,
            'bill_no' => $row['bill_no'],
        ], 200);
    }

    public function storeBatch(Request $request)
    {
        $branch = $this->branchFromBearerToken($request);

        $payload = $request->validate([
            'invoices' => 'required|array|min:1',
            'invoices.*.bill_no'      => 'required|string|max:50',
            'invoices.*.bill_date'    => 'required|string',
            'invoices.*.grand_total'  => 'required|numeric',
            'invoices.*.discount_per' => 'nullable|numeric',
            'invoices.*.payment_mode' => 'nullable|string|max:50',
            'invoices.*.operator'     => 'nullable|string|max:100',
            'invoices.*.status'       => 'nullable|string|max:20',
        ]);

        $rows = [];
        foreach ($payload['invoices'] as $inv) {
            $rows[] = [
                'branch_id'     => (int)$branch->id,
                'bill_no'       => $inv['bill_no'],
                'bill_date'     => $this->normalizeBillDate($inv['bill_date']),
                'grand_total'   => (float)$inv['grand_total'],
                'discount_per'  => (float)($inv['discount_per'] ?? 0),
                'payment_mode'  => $inv['payment_mode'] ?? null,
                'operator'      => $inv['operator'] ?? null,
                'status'        => $inv['status'] ?? null,
                'created_at'    => now(),
                'updated_at'    => now(),
            ];
        }

        DB::table('sales_invoices')->upsert(
            $rows,
            ['branch_id', 'bill_no'],
            ['bill_date','grand_total','discount_per','payment_mode','operator','status','updated_at']
        );

        return response()->json([
            'ok' => true,
            'branch_id' => (int)$branch->id,
            'count' => count($rows),
        ], 200);
    }
}
