<?php
namespace App\Http\Controllers;
use App\Models\{Project,User,Plan,Department,Task,Correction,FormRevision};
use App\Services\{Access,ProjectFlow,Notify,Points,Dates};
use Illuminate\Http\Request;
class ProjectsController {
 public function index(Request $r){$q=Project::visibleTo($r->user())->with(['customer','mentor'])->latest();if($r->filled('q'))$q->where(function($q)use($r){$q->where('name','like','%'.$r->q.'%')->orWhere('site_url','like','%'.$r->q.'%');});if($r->filled('status'))$q->where('status',$r->status);return view('projects.index',['projects'=>$q->paginate(12),'plans'=>Plan::where('kind','mentoring')->get()]);}
 public function show(Request $r,Project $project){Access::project($r->user(),$project);$project->load(['customer','mentor']);$activities=$project->activities()->when(!$r->user()->isStaff(),fn($q)=>$q->where('visible',true))->paginate(20);$tasks=$project->tasks()->when(!$r->user()->isStaff(),fn($q)=>$q->where('visible',true))->get();return view('projects.show',compact('project','activities','tasks'));}
 public function create(Request $r){$v=$r->validate(['name'=>'required|max:160','department_id'=>'nullable|exists:departments,id','login_url'=>'nullable|required_with:wp_password|url|max:250','wp_username'=>'nullable|required_with:wp_password|string|max:200','wp_password'=>'nullable|string|max:500','site_url'=>'nullable|url|max:250','description'=>'nullable|string|max:6000','internal_note'=>'nullable|string|max:6000','customer_id'=>'nullable|integer','mentor_id'=>'nullable|integer','plan_id'=>'nullable|integer','start_date'=>'nullable|string','end_date'=>'nullable|string']);if($r->user()->isManager())$r->validate(['customer_id'=>'required|integer','mentor_id'=>'required|integer','plan_id'=>'required|integer','start_date'=>'required','end_date'=>'required']);$p=app(ProjectFlow::class)->create($r->user(),$v);return redirect('/projects/'.$p->id)->with('success','پروژه ثبت شد. همراه مسیر شما هستیم.');}
 public function activate(Request $r,Project $project){$v=$r->validate(['mentor_id'=>'required|integer','plan_id'=>'required|integer','start_date'=>'required|string','end_date'=>'required|string','internal_note'=>'nullable|string|max:6000']);app(ProjectFlow::class)->activate($r->user(),$project,$v);return back()->with('success','پروژه فعال و به منتور معرفی شد.');}
 public function gift(Request $r,Project $project){$v=$r->validate(['days'=>'required|integer|between:1,365','reason'=>'required|string|min:5|max:2000']);app(ProjectFlow::class)->gift($r->user(),$project,$v['days'],$v['reason']);return back()->with('success','دوره هدیه ثبت شد.');}
 public function dates(Request $r,Project $project){$v=$r->validate(['start_date'=>'required|string','end_date'=>'required|string','reason'=>'required|string|min:5|max:2000']);app(ProjectFlow::class)->dates($r->user(),$project,$v['start_date'],$v['end_date'],$v['reason']);return back()->with('success','بازه پروژه اصلاح شد.');}
 public function action(Request $r,Project $project){$v=$r->validate(['action'=>'required|string','reason'=>'required|string|min:5|max:2000']);app(ProjectFlow::class)->transition($r->user(),$project,$v['action'],$v['reason']);return back()->with('success','وضعیت پروژه به‌روزرسانی شد.');}
 public function assign(Request $r,Project $project){$v=$r->validate(['mentor_id'=>'required|integer','reason'=>'required|string|min:5']);app(ProjectFlow::class)->assign($r->user(),$project,$v['mentor_id'],$v['reason']);return back()->with('success','مسئول جدید معرفی شد.');}
 public function credentials(Request $r,Project $project){Access::project($r->user(),$project);abort_unless($r->user()->id===$project->customer_id||$r->user()->canAdmin('credentials'),403);$v=$r->validate(['login_url'=>'required|url|max:250','username'=>'required|string|max:200','password'=>'required|string|max:500']);$project->update(['credentials'=>$v]);Access::audit('credentials_updated',$project->id);return back()->with('success','اطلاعات ورود به‌صورت امن ذخیره شد.');}
 public function reveal(Request $r,Project $project){Access::project($r->user(),$project);abort_unless($r->user()->id===$project->customer_id||$r->user()->id===$project->mentor_id||$r->user()->canAdmin('credentials'),403);$r->validate(['password'=>'required']);abort_unless(\Illuminate\Support\Facades\Hash::check($r->password,$r->user()->password),403,'رمز حساب باشگاه درست نیست.');Access::audit('credentials_viewed',$project->id);return response()->view('projects.credentials',['project'=>$project,'credentials'=>$project->credentials??[]])->header('Cache-Control','no-store');}
 public function task(Request $r,Project $project){Access::project($r->user(),$project);abort_unless($r->user()->isStaff(),403);$v=$r->validate(['title'=>'required|string|min:5|max:200','description'=>'nullable|string|max:3000','due_date'=>'nullable|string','kind'=>'required|in:task,product,page,followup','visible'=>'nullable|boolean']);Task::create(['project_id'=>$project->id,'user_id'=>$r->user()->id,'title'=>$v['title'],'description'=>$v['description']??null,'due_at'=>!empty($v['due_date'])?Dates::parse($v['due_date'],true):null,'kind'=>$v['kind'],'visible'=>$r->boolean('visible')]);return back()->with('success','کار بعدی مشخص شد.');}
 public function completeTask(Request $r,Project $project,Task $task){Access::project($r->user(),$project);abort_unless($r->user()->isStaff()&&$task->project_id===$project->id,403);$v=$r->validate(['result_url'=>'nullable|url','result'=>'required|string|min:5|max:2000']);if(!$task->completed_at){$task->update(['status'=>'done','completed_at'=>now(),'result_url'=>$v['result_url']??null]);app(ProjectFlow::class)->activity($project,$r->user(),'task_done',$task->title.' · '.$v['result'],true,$task->visible);}return back();}
 public function correction(Request $r,Project $project){Access::project($r->user(),$project);abort_unless($r->user()->isStaff(),403);$v=$r->validate(['fields'=>'required|array','fields.*'=>'required|string','reason'=>'required|string|min:5']);abort_unless(!array_diff($v['fields'],array_keys(config('intake.fields'))),422);$c=Correction::create(['project_id'=>$project->id,'user_id'=>$r->user()->id,'fields'=>$v['fields'],'reason'=>$v['reason']]);app(Notify::class)->event('correction',$project,[],"correction:$c->id");return back()->with('success','موارد نیازمند تکمیل برای مشتری ارسال شد.');}
 public function approveForm(Request $r,Project $project){Access::project($r->user(),$project);abort_unless($r->user()->isStaff()&&$project->submitted_at,403);$project->update(['form_status'=>'accepted']);app(Points::class)->award($project->customer,'intake','project:'.$project->id);return back()->with('success','اطلاعات تأیید و امتیاز ثبت شد.');}
 public function history(Request $r,Project $project){Access::project($r->user(),$project);return view('projects.history',['project'=>$project,'revisions'=>FormRevision::where('project_id',$project->id)->latest('version')->get()]);}
}
