<?php

namespace App\Http\Controllers\API\v1;

use App\Http\Controllers\Controller;
use App\Models\Customer;
use Illuminate\Http\Request;
use Exception;
use Illuminate\Database\QueryException;
use Illuminate\Support\Facades\DB;
use Symfony\Component\HttpFoundation\Response as HttpFoundationResponse;

class CustomerController extends Controller
{
    public function index(Request $request)
    {
        $data = null;
        $status = '';
        $req_status = 0;
        $message = '';

        try {
            $data = Customer::select(
                DB::raw('phone as memberCode'),
                'nama as fullname',
                'email as email',
                'phone as phoneNumber',
                // DB::raw('null as membershipType'),
                DB::raw('null as dateOfBirth, date(created_at) as registerDate, concat("(",mc.category,") Cashback ",mc.percent,"%") as membershipType'),
                // 'created_at as registerDate',
                'poin as poin',
            )
            ->join('member_categories as mc','customer.category_id','mc.id')
            ->where('phone', $request->phoneNumber)
            ->firstOrFail();
            $req_status = HttpFoundationResponse::HTTP_OK;
            $status = true;
            $message = 'Success';
        } catch (Exception $e) {
            $req_status = HttpFoundationResponse::HTTP_NOT_FOUND;
            $status = false;
            $message = 'Member not found';
        } catch (QueryException $e) {
            $req_status = HttpFoundationResponse::HTTP_NOT_FOUND;
            $status = false;
            $message = 'Member not found';
        } finally {
            $response = [
                'message' => $message,
                'status' => $status,
                'statusCode' => $req_status,
            ];
            if ($req_status == HttpFoundationResponse::HTTP_OK) {
                $response['data'] = $data;
            }
            return response()->json($response, $req_status);
        }
    }
}
