<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Services\StorageChargeService;
use App\StorageContract;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;

class StorageContractController extends Controller
{
    const ITEM_PER_PAGE = 50;

    /**
     * 保管契約一覧（フィルタ付き）
     */
    public function index(Request $request)
    {
        $searchParams = $request->all();
        $limit = Arr::get($searchParams, 'limit', static::ITEM_PER_PAGE);
        $keyword = Arr::get($searchParams, 'keyword', '');
        $status = Arr::get($searchParams, 'status', '');
        $renewalFrom = Arr::get($searchParams, 'renewal_from', '');
        $renewalTo = Arr::get($searchParams, 'renewal_to', '');
        $startFrom = Arr::get($searchParams, 'start_from', '');
        $startTo = Arr::get($searchParams, 'start_to', '');
        $createdFrom = Arr::get($searchParams, 'created_from', '');
        $createdTo = Arr::get($searchParams, 'created_to', '');

        $list = StorageContract::with(['user', 'product']);

        if (!empty($keyword)) {
            $list->where(function ($query) use ($keyword) {
                $query->where('id', '=', $keyword)
                    ->orWhereHas('user', function ($userQuery) use ($keyword) {
                        $userQuery->where('name', 'LIKE', '%' . $keyword . '%')
                            ->orWhere('full_name', 'LIKE', '%' . $keyword . '%')
                            ->orWhere('furigana_name', 'LIKE', '%' . $keyword . '%');
                    })
                    ->orWhereHas('product', function ($productQuery) use ($keyword) {
                        $productQuery->where('name', 'LIKE', '%' . $keyword . '%');
                    });
            });
        }

        if ($status !== '' && $status !== null) {
            $list->where('status', (int)$status);
        }

        if (!empty($renewalFrom)) {
            $list->where('next_renewal_date', '>=', $renewalFrom);
        }

        if (!empty($renewalTo)) {
            $list->where('next_renewal_date', '<=', $renewalTo);
        }

        if (!empty($startFrom)) {
            $list->where('storage_start_date', '>=', $startFrom);
        }
        if (!empty($startTo)) {
            $list->where('storage_start_date', '<=', $startTo);
        }
        if (!empty($createdFrom)) {
            $list->whereDate('created_at', '>=', $createdFrom);
        }
        if (!empty($createdTo)) {
            $list->whereDate('created_at', '<=', $createdTo);
        }

        $list->orderBy('id', 'DESC');

        return response()->json($list->paginate($limit));
    }

    /**
     * 保管契約詳細
     */
    public function show($id)
    {
        $contract = StorageContract::with(['user', 'product'])->find($id);
        if (!$contract) {
            return response()->json(['errors' => '契約が見つかりません'], 404);
        }

        // 課金履歴（保管料: type=2, 保管料更新: type=3）
        // この契約に紐づく履歴のみ表示。同一ユーザーの他契約の課金は除外。
        $paymentHistories = \App\UserPaymentHistory::where('storage_contract_id', $contract->id)
            ->whereIn('type', [2, 3])
            ->orderBy('created_at', 'DESC')
            ->get();

        $data = $contract->toArray();
        $data['payment_histories'] = $paymentHistories;
        $data['renewal_notice_due_on'] = $contract->next_renewal_date
            ? Carbon::parse($contract->next_renewal_date)->subMonth()->toDateString()
            : null;

        return response()->json($data);
    }

    /**
     * 担当者メモを更新
     */
    public function updateNote(Request $request, $id)
    {
        $contract = StorageContract::find($id);
        if (!$contract) {
            return response()->json(['errors' => '契約が見つかりません'], 404);
        }

        $validated = $request->validate([
            'admin_note' => ['nullable', 'string', 'max:5000'],
        ]);

        $contract->update([
            'admin_note' => $validated['admin_note'] ?? null,
        ]);

        return response()->json([
            'status' => 'success',
            'contract' => $contract->fresh(['user', 'product']),
        ]);
    }

    /**
     * 課金履歴の確認メモを更新
     */
    public function updatePaymentNote(Request $request, $contractId, $historyId)
    {
        $contract = StorageContract::find($contractId);
        if (!$contract) {
            return response()->json(['errors' => '契約が見つかりません'], 404);
        }

        $history = \App\UserPaymentHistory::where('id', $historyId)
            ->where('storage_contract_id', $contract->id)
            ->first();
        if (!$history) {
            return response()->json(['errors' => '課金履歴が見つかりません'], 404);
        }

        $validated = $request->validate([
            'note' => ['nullable', 'string', 'max:2000'],
        ]);

        $history->update(['note' => $validated['note'] ?? null]);

        return response()->json(['status' => 'success', 'history' => $history->fresh()]);
    }

    /**
     * 契約を解約
     */
    public function cancel($id)
    {
        $contract = StorageContract::find($id);
        if (!$contract) {
            return response()->json(['errors' => '契約が見つかりません'], 404);
        }

        $service = new StorageChargeService();
        $service->cancelContract($contract);

        return response()->json([
            'status' => 'success',
            'contract' => $contract->fresh(['user', 'product']),
        ]);
    }
}
