<?php
namespace App\Http\Controllers;
use App\Models\PriceBook;
use App\Models\PriceBookItem;
use App\Models\Product;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
class PriceBookController extends Controller {
 public function index(Request $request){
  $this->authorizeUser($request);$books=PriceBook::with('items.product')->latest()->get();
  $products=Product::where('business_id',$request->user()->business_id)->orderBy('product_name')->get();
  return view('products.price-books',compact('books','products'));
 }
 public function store(Request $request){
  $this->authorizeUser($request);$data=$request->validate(['name'=>'required|string|max:255','currency'=>'required|string|max:8','active'=>'nullable|boolean']);
  PriceBook::create($data+['business_id'=>$request->user()->business_id,'active'=>$request->boolean('active',true)]);
  return back()->with('success','Price Book created.');
 }
 public function update(Request $request,PriceBook $priceBook){
  $this->authorizeBook($request,$priceBook);$data=$request->validate(['name'=>'required|string|max:255','currency'=>'required|string|max:8','active'=>'nullable|boolean']);
  $priceBook->update($data+['active'=>$request->boolean('active')]);return back()->with('success','Price Book updated.');
 }
 public function destroy(Request $request,PriceBook $priceBook){
  $this->authorizeBook($request,$priceBook);$priceBook->delete();return back()->with('success','Price Book archived.');
 }
 public function storeItem(Request $request,PriceBook $priceBook){
  $this->authorizeBook($request,$priceBook);$data=$request->validate([
   'product_id'=>['required',Rule::exists('products','id')->where('business_id',$request->user()->business_id)],
   'unit_price'=>'required|numeric|min:0','max_discount_percent'=>'required|numeric|min:0|max:100']);
  $priceBook->items()->updateOrCreate(['product_id'=>$data['product_id']],$data);
  return back()->with('success','Price Book item saved.');
 }
 public function destroyItem(Request $request,PriceBook $priceBook,PriceBookItem $item){
  $this->authorizeBook($request,$priceBook);abort_unless($item->price_book_id===$priceBook->id,404);$item->delete();
  return back()->with('success','Price Book item removed.');
 }
 private function authorizeUser(Request $request):void{abort_unless($request->user()->is_admin||$request->user()->can('update_products'),403);}
 private function authorizeBook(Request $request,PriceBook $book):void{$this->authorizeUser($request);abort_unless($book->business_id===$request->user()->business_id,403);}
}
