<?php

namespace App\Http\Controllers\Api;

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

class CustomerKtpController extends Controller
{
    public function upload(Request $request, $id)
    {
        // Validasi hanya untuk foto, tidak menyentuh field lain
        $request->validate([
            'ktp_photo' => 'required|image|mimes:jpeg,png,jpg|max:2048'
        ]);

        try {
            $user = $request->user();
            $customer = Customer::findOrFail($id);

            // PENAMBAHAN: Proteksi Hak Akses Cabang (Isolasi Data Dokumen Sensitif)
            // Mencegah admin cabang menimpa/merubah KTP pelanggan dari cabang lain
            if ($user && $user->role !== 'owner' && $customer->branch_id !== $user->branch_id) {
                return response()->json([
                    'success' => false,
                    'message' => 'Akses ditolak: Anda tidak memiliki hak akses untuk mengubah KTP pelanggan dari cabang lain.'
                ], 403);
            }

            // Simpan file baru
            if ($request->hasFile('ktp_photo')) {
                // Hapus file lama jika ada
                if ($customer->ktp_path) {
                    Storage::disk('public')->delete($customer->ktp_path);
                }
                
                $path = $request->file('ktp_photo')->store('ktp_data', 'public');
                $customer->update(['ktp_path' => $path]);
            }
            
            return response()->json([
                'success' => true,
                'message' => 'Upload KTP berhasil'
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false, 
                'message' => 'Terjadi kesalahan saat mengunggah KTP: ' . $e->getMessage()
            ], 500);
        }
    }
}