<?php

namespace App\Http\Controllers;

use App\Models\Policy;
use App\Models\UserPolicyAcceptance;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Barryvdh\DomPDF\Facade\Pdf;




class PolicyController extends Controller

{
    // ADMIN VIEW
    public function adminIndex()
    {
        $policies = Policy::latest()->get();
        return view('admin.policies.index', compact('policies'));
    }

    public function create()
    {
        return view('admin.policies.create');
    }

    public function edit(Policy $policy)
{
    return view('admin.policies.edit', compact('policy'));
}


// UPDATE POLICY
public function update(Request $request, Policy $policy)
{
    $request->validate([
        'title'       => 'required|string|max:255',
        'description' => 'nullable|string',
        'content'     => 'required|string',
        'version'     => 'nullable|string|max:50',
    ]);

    $data = $request->only(['title', 'description', 'content', 'version']);

    // Convert checkbox to boolean
    $data['is_active'] = $request->boolean('is_active') ? 1 : 0;

    $policy->update($data);

    return redirect()
        ->route('admin.policies.index')
        ->with('success', 'Policy updated successfully.');
}


public function store(Request $request)
{
    $request->validate([
        'title'       => 'required|string|max:255',
        'description' => 'nullable|string',
        'content'     => 'required|string',
        'version'     => 'nullable|string|max:50',
    ]);

    // normalize input
    $data = $request->only(['title', 'description', 'content', 'version']);

    // Convert checkbox to boolean/int
    // Option A (Laravel helper): returns true/false
    $data['is_active'] = $request->boolean('is_active') ? 1 : 0;

    // Option B (if you prefer explicit check):
    // $data['is_active'] = $request->has('is_active') ? 1 : 0;

    Policy::create($data);

    return redirect()->route('admin.policies.index')
        ->with('success', 'Policy created successfully.');
}

   

public function memberIndex()
{
    $user = Auth::user();

    // only active policies for members
    $policies = Policy::where('is_active', 1)->latest()->get();

    // fetch policy ids the user already agreed to
    // we only need the ids for the view check
    $userAgreements = UserPolicyAcceptance::where('user_id', $user->id)
        ->pluck('policy_id')
        ->toArray();

    return view('member.policies.index', compact('policies', 'userAgreements'));
}

/**
 * MEMBER: Record acceptance of a policy.
 * POST /member/policies/{policy}/agree
 */
public function agree(Request $request, Policy $policy)
{
    $userId = Auth::id();

    // We'll store the policy version at the time of agreement (if present)
    $version = $policy->version ?? null;

    // firstOrCreate to avoid duplicates (idempotent)
    $acceptance = UserPolicyAcceptance::firstOrCreate(
        [
            'user_id'   => $userId,
            'policy_id' => $policy->id,
        ],
        [
            // extra fields to fill if record doesn't exist
            'policy_version' => $version,
            'agreed_at'      => now(),
            'ip_address'     => $request->ip(),
        ]
    );

    // Optional: you can also update an existing acceptance to the latest version/time
    // uncomment below if you want to refresh agreed_at & version when user clicks again
    /*
    $acceptance->update([
        'policy_version' => $version,
        'agreed_at'      => now(),
        'ip_address'     => $request->ip(),
    ]);
    */

    return redirect()->route('member.policies.index')
        ->with('success', 'Thanks — you have agreed to the policy.');
}




public function memberPdf(Policy $policy)
{
    // Ensure only active policies can be downloaded
    if (!$policy->is_active) {
        abort(403, 'This policy is not active.');
    }

    $user = auth()->user();

    $pdf = Pdf::loadView('member.policies.pdf', [
        'policy' => $policy,
        'user'   => $user,
    ])->setPaper('A4', 'portrait');

    $fileName = 'Policy-' . $policy->title . '.pdf';

    return $pdf->download($fileName);
}

}
