<?php
namespace App\Http\Controllers;
use App\Models\{Project,Ticket,Message,Attachment};
use App\Services\{Access,ProjectFlow,Notify};
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class TicketsController {
 public function index(Request $r){$q=Ticket::with(['project','user'])->latest();if($r->user()->role!=='admin')$q->where(function($q)use($r){$q->where('user_id',$r->user()->id)->orWhereIn('project_id',Project::visibleTo($r->user())->select('id'));});return view('tickets',['tickets'=>$q->paginate(20),'projects'=>Project::visibleTo($r->user())->get()]);}
 public function create(Request $r){$v=$r->validate(['subject'=>'required|string|max:180','body'=>'required|string|min:5|max:10000','kind'=>'required|in:mentoring,form_help,finance,logo,account','project_id'=>'nullable|integer','request_key'=>'required|uuid']);$p=$r->project_id?Project::findOrFail($r->project_id):null;if($p)Access::project($r->user(),$p);if($v['kind']==='mentoring')abort_unless($p?->isActive()&&$p->submitted_at,422,'پس از ارسال نهایی اطلاعات و در زمان فعال منتورینگ، تیکت آزاد در دسترس است.');
  $t=DB::transaction(function()use($r,$v,$p){$old=Message::where('request_key',$v['request_key'])->first();if($old){abort_unless($old->user_id===$r->user()->id,403);return Ticket::findOrFail($old->ticket_id);}$t=Ticket::create(['user_id'=>$r->user()->id,'project_id'=>$p?->id,'service_period_id'=>$p?->currentPeriod()?->id,'subject'=>$v['subject'],'kind'=>$v['kind']]);$this->message($r,$t,$v);return $t;});return redirect('/tickets/'.$t->id)->with('success','پیامتان رسید؛ همراه شما هستیم.');
 }
 public function show(Request $r,Ticket $ticket){Access::ticket($r->user(),$ticket);$messages=$ticket->messages()->with('user')->when(!$r->user()->isStaff(),fn($q)=>$q->where('internal',false))->oldest()->get();return view('ticket',compact('ticket','messages'));}
 public function reply(Request $r,Ticket $ticket){Access::ticket($r->user(),$ticket);$v=$r->validate(['body'=>'required|string|min:2|max:10000','request_key'=>'required|uuid','internal'=>'nullable|boolean']);if(!$r->user()->isStaff()&&$ticket->kind==='mentoring')abort_unless($ticket->project?->isActive(),422,'برای ادامه گفت‌وگوی منتورینگ، دوره را تمدید کنید.');abort_unless(!$r->boolean('internal')||$r->user()->isStaff(),403);$this->message($r,$ticket,$v);return back()->with('success','پیام ثبت شد.');}
 private function message(Request $r,Ticket $t,array $v):void {$m=Message::firstOrCreate(['request_key'=>$v['request_key']],['ticket_id'=>$t->id,'user_id'=>$r->user()->id,'body'=>$v['body'],'internal'=>$r->boolean('internal')]);if(!$m->wasRecentlyCreated)return;$next=$r->user()->isStaff()?'waiting_customer':'waiting_mentor';if(!$m->internal)$t->update(['status'=>$next,'waiting_since'=>$t->status!==$next||!$t->waiting_since?now():$t->waiting_since,'resolved_at'=>null]);if($t->project&&!$m->internal){app(ProjectFlow::class)->activity($t->project,$r->user(),'message','پیام تازه‌ای در گفت‌وگوی پروژه ثبت شد.',true);$other=$r->user()->isStaff()?$t->project->customer:$t->project->mentor;app(Notify::class)->event('ticket_message',$t->project,['ticket_number'=>$t->id,'ticket_url'=>url('/tickets/'.$t->id)],"message:$m->id",$other);}}
 public function close(Request $r,Ticket $ticket){Access::ticket($r->user(),$ticket);$ticket->update(['status'=>'resolved','resolved_at'=>now(),'waiting_since'=>null]);return back();}
}
