<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;

class DonationsController extends Controller
{
    /**
     * Store a new donation and transaction.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\JsonResponse
     */
     // Add this to DonationsController.php

/**
 * Display a listing of donations with completed transactions.
 *
 * @return \Illuminate\Http\JsonResponse
 */
public function index()
{
    // Fetch donations and their details
    $donations = DB::table('donations')
        ->join('transactions', 'donations.transaction_id', '=', 'transactions.id')
        ->join('users', 'donations.user_id', '=', 'users.user_id') // FIXED JOIN CONDITION
        ->where('transactions.status', 'completed')
        ->select(
            'donations.id as donation_id',
            'users.name as user_name',
            'donations.user_id', 
            'donations.amount',
            'donations.donation_date',
            'transactions.status as transaction_status',
            'transactions.payment_method'
        )
        ->get();

    // Calculate the total amount of completed donations
    $totalDonations = $donations->sum('amount');

    return view('donations.index', compact('donations', 'totalDonations'));
}



public function store(Request $request)
{
    $validator = Validator::make($request->all(), [
        'transaction_id' => 'required|exists:transactions,id',
        'amount' => 'required|numeric|min:0.01',
    ]);

    if ($validator->fails()) {
        return response()->json(['errors' => $validator->errors()], 422);
    }

    DB::beginTransaction();

    try {
        $userId = $request->user()->user_id;

        // Fetch the transaction details
        $transaction = DB::table('transactions')
            ->where('id', $request->transaction_id)
            ->where('user_id', $userId)
            ->first();

        if (!$transaction) {
            return response()->json(['error' => 'Invalid transaction ID or unauthorized access.'], 403);
        }

        if ($transaction->status !== 'completed') {
            return response()->json(['message' => 'Payment is still pending. Donation cannot be recorded.'], 400);
        }

        // Ensure donation amount exactly matches the transaction amount
        if ($request->amount != $transaction->amount) {
            return response()->json(['error' => 'Donation amount must be exactly equal to the transaction amount.'], 400);
        }

        // Check if a donation already exists for this transaction
        $existingDonation = DB::table('donations')
            ->where('transaction_id', $transaction->id)
            ->exists();

        if ($existingDonation) {
            return response()->json(['message' => 'Donation already recorded for this transaction.'], 409);
        }

        // Insert into the donations table
        $donationId = DB::table('donations')->insertGetId([
            'user_id' => $userId,
            'transaction_id' => $transaction->id,
            'amount' => $request->amount,
            'donation_date' => now(),
            'created_at' => now(),
            'updated_at' => now(),
        ]);

        DB::commit();

        return response()->json([
            'message' => 'Donation recorded successfully.',
            'donation_id' => $donationId,
            'transaction_id' => $transaction->id,
        ], 201);

    } catch (\Exception $e) {
        DB::rollBack();
        return response()->json(['error' => 'Failed to record donation.', 'message' => $e->getMessage()], 500);
    }
}





    /**
     * Update an existing donation.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function update(Request $request, $id)
    {
        $validator = Validator::make($request->all(), [
            'amount' => 'required|numeric|min:0.01',
        ]);

        if ($validator->fails()) {
            return response()->json(['errors' => $validator->errors()], 422);
        }

        $donation = DB::table('donations')->where('id', $id)->first();

        if (!$donation || $donation->user_id !== $request->user()->id) {
            return response()->json(['message' => 'Donation not found or unauthorized'], 404);
        }

        DB::table('donations')->where('id', $id)->update([
            'amount' => $request->amount,
            'updated_at' => now(),
        ]);

        return response()->json(['message' => 'Donation updated successfully'], 200);
    }

    /**
     * Delete a donation.
     *
     * @param  int  $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function delete($id)
    {
        $donation = DB::table('donations')->where('id', $id)->first();

        if (!$donation || $donation->user_id !== auth()->id()) {
            return response()->json(['message' => 'Donation not found or unauthorized'], 404);
        }

        DB::table('donations')->where('id', $id)->delete();

        return response()->json(['message' => 'Donation deleted successfully'], 200);
    }
}
