<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Customer;
use Illuminate\Support\Facades\Log;

class SalesmanCustomerController extends Controller
{
    /**
     * Update data master pelanggan khusus dari aplikasi mobile salesman (Extra Call)
     * Mencegah data penting terhapus karena perbedaan format request multipart form-data.
     */
    public function updateFromMobile(Request $request, $id)
    {
        $user = $request->user();

        // ========================================================================
        // PERBAIKAN ENTERPRISE: Keamanan Isolasi Cabang (Branch Data Isolation)
        // ========================================================================
        $query = Customer::query();
        if ($user && $user->role !== 'owner') {
            $query->where('branch_id', $user->branch_id);
            
            // Opsi Tambahan Ultra-Strict: 
            // Jika Anda ingin Salesman HANYA bisa mengedit pelanggan yang ditugaskan kepadanya:
            // if ($user->role === 'salesman') {
            //     $query->where('salesman_id', $user->salesman_id);
            // }
        }
        
        // Gunakan firstOrFail agar melempar 404 jika ID pelanggan ada tapi beda cabang
        $customer = $query->where('id', $id)->firstOrFail();
        // ========================================================================

        // PERBAIKAN 1: latitude dan longitude disesuaikan menjadi numeric (sesuai tipe decimal di DB)
        $request->validate([
            'name' => 'required|string|max:255',
            'owner_name' => 'nullable|string|max:255',
            'phone' => 'nullable|string|max:20',
            'address' => 'required|string',
            'benchmark' => 'nullable|string',
            'latitude' => 'nullable|numeric',
            'longitude' => 'nullable|numeric',
            'no_ktp' => 'nullable|string|max:20',
        ]);

        try {
            // Ambil data kiriman murni, abaikan file foto untuk payload text
            $data = $request->except(['ktp_photo']);

            // Siapkan payload penampung update
            $updatePayload = [];

            // 1. FIELD WAJIB (Selalu Update)
            $updatePayload['name'] = strtoupper($data['name']);
            $updatePayload['address'] = strtoupper($data['address']);

            // 2. FIELD TEKS OPSIONAL
            // PERBAIKAN 2: Menggunakan has() agar aplikasi mobile bisa mengosongkan data (null) jika diinginkan
            $updatePayload['owner_name'] = $request->has('owner_name') ? (!empty($data['owner_name']) ? strtoupper($data['owner_name']) : null) : $customer->owner_name;
            $updatePayload['phone']      = $request->has('phone') ? (!empty($data['phone']) ? $data['phone'] : null) : $customer->phone;
            $updatePayload['benchmark']  = $request->has('benchmark') ? (!empty($data['benchmark']) ? strtoupper($data['benchmark']) : null) : $customer->benchmark;
            $updatePayload['latitude']   = $request->has('latitude') ? (!empty($data['latitude']) ? $data['latitude'] : null) : $customer->latitude;
            $updatePayload['longitude']  = $request->has('longitude') ? (!empty($data['longitude']) ? $data['longitude'] : null) : $customer->longitude;
            $updatePayload['no_ktp']     = $request->has('no_ktp') ? (!empty($data['no_ktp']) ? $data['no_ktp'] : null) : $customer->no_ktp;

            // 3. PROTEKSI DATA VITAL FINANSIAL DAN RELASI ERP
            // Menjamin field ini TETAP memakai data lama di database dan TIDAK BOLEH dikosongkan oleh aplikasi mobile
            $updatePayload['branch_id']           = $customer->branch_id;
            $updatePayload['salesman_id']         = $customer->salesman_id;
            $updatePayload['district_id']         = $customer->district_id;
            $updatePayload['customer_type_id']    = $customer->customer_type_id;
            $updatePayload['price_level']         = $customer->price_level;
            $updatePayload['credit_limit']        = $customer->credit_limit;
            $updatePayload['due_days']            = $customer->due_days;
            $updatePayload['is_pkp']              = $customer->is_pkp;
            $updatePayload['default_tax_method']  = $customer->default_tax_method;
            $updatePayload['npwp']                = $customer->npwp;
            $updatePayload['is_active']           = $customer->is_active;
            $updatePayload['registration_status'] = $customer->registration_status;
            $updatePayload['join_date']           = $customer->join_date;

            // 4. PROSES UPDATE DATA TEXT
            $customer->update($updatePayload);

            return response()->json([
                'success' => true,
                'message' => 'Maintenance data pelanggan dari lapangan berhasil disinkronkan',
                'data' => $customer
            ], 200);

        } catch (\Exception $e) {
            Log::error("Mobile Customer Update Error: " . $e->getMessage());
            return response()->json([
                'success' => false,
                'message' => 'Gagal Sinkronisasi DMS Mobile: ' . $e->getMessage()
            ], 500);
        }
    }
}