<?php

namespace App\Http\Controllers;

use App\Models\Block;
use App\Models\District;
use App\Models\Member;
use App\Models\User;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;
use Symfony\Component\HttpFoundation\StreamedResponse;

class MemberController extends Controller
{
    public function index()
    {
        $districts = District::all();
        $blocks = Block::all();
        return view('admin.member_list')->with(['districts' => $districts,'blocks' => $blocks]);
    }

    public function getUserList(Request $request)
    {
        $query = Member::select(
            'member_id',
            'member_name',
            'member_phone',
            'member_email',
            'district_id',
            'block_id',
            'dob',
            'photo_url',
            'doj',
            'designation',
            'panchayat',
            'jivika_name',
            'member_sh_id',
            'address',
            'status'
        )
            ->with([
                'district:id,district_name',
                'block:block_id,block_name',
                'createdBy:id,name'
            ]);

        // 🔹 Filter: District
        if ($request->district_id) {
            $query->where('district', $request->district_id);
        }

        // 🔹 Filter: Block
        if ($request->block_id) {
            $query->where('block', $request->block_id);
        }

        // 🔹 Filter: Status
        if (!is_null($request->status)) {
            $query->where('status', $request->status);
        }

        // 🔹 Search
        if (!empty($request->search['value'])) {
            $search = $request->search['value'];
            $query->where(function ($q) use ($search) {
                $q->where('member_name', 'LIKE', "%$search%")
                    ->orWhere('member_phone', 'LIKE', "%$search%")
                    ->orWhere('member_email', 'LIKE', "%$search%")
                    ->orWhereHas('district', function ($sub) use ($search) {
                        $sub->where('district_name', 'LIKE', "%$search%");
                    })
                    ->orWhereHas('block', function ($sub) use ($search) {
                        $sub->where('block_name', 'LIKE', "%$search%");
                    });
            });
        }

       
        $count = $query->count();
        $result = $query
            ->skip($request->start ?? 0)
            ->limit($request->length ?? 10)
            ->orderBy('member_id', 'desc')
            ->get();


        return DatatableResponse($result, $count, $request->draw);
    }

    public function create()
    {
        $districts = District::all();
        $blocks = Block::where('district_id', Session::get('user_district'))->get();
        return view('admin.member')->with(['districts' => $districts,'blocks' => $blocks]);
    }

    public function store(Request $request)
    {
        $request->validate([
            'name'          => 'required|string|max:255',
            'phone_number'  => 'required|string|max:15',
            'status'        => 'required',
            'block'         => 'required',
        ]);

        $user = new Member();
        $user->member_name = $request->name;
        $user->member_phone = $request->phone_number;
        $user->father_name = $request->father_name;
        $user->member_sh_id = $request->member_sh_id;

        $user->member_email = $request->email;
        $user->district_id = $request->district;
        $user->block_id = $request->block;

        $user->dob = $request->dob;
        $user->doj = $request->doj;
        $user->designation = $request->designation;
        $user->panchayat = $request->panchayat;
        $user->address = $request->address;
        $user->jivika_name = $request->jivika;
        $user->shg_id = $request->shg_id;

        if ($request->hasFile('photo')) {
            $image = $request->file('photo');
            $originalName = pathinfo($image->getClientOriginalName(), PATHINFO_FILENAME);
            $safeName = Str::slug($originalName);
            $extension = $image->getClientOriginalExtension();
            $filename = time() . '_' . $safeName . '.' . $extension;
            $user->photo_url = $filename;
        }

        $user->status = $request->status;
        $user->created_at = date('Y-m-d H:i:s');
        $user->created_by = Session::get('user_id');
        $user->report_to = Session::get('user_id');
        $user->save();

        return apiResponse('success', 'Member created successfully!', null);
    }

    public function update(Request $request, $id)
    {
        $request->validate([
            'name'          => 'required|string|max:255',
            'phone_number'  => 'required|string|max:15',
            'status'        => 'required',
            'block'         => 'required',
        ]);

        $user = Member::findOrFail($id);
        $user->member_name = $request->name;
        $user->father_name = $request->father_name;
        $user->member_sh_id = $request->member_sh_id;
        $user->member_phone = $request->phone_number;
        $user->member_email = $request->email;
        $user->district_id = $request->district;
        $user->block_id = $request->block;
        $user->status = $request->status;

        $user->dob = $request->dob;
        $user->doj = $request->doj;
        $user->designation = $request->designation;
        $user->panchayat = $request->panchayat;
        $user->address = $request->address;
        $user->jivika_name = $request->jivika;
        $user->shg_id = $request->shg_id;


        if ($request->hasFile('photo')) {
            $image = $request->file('photo');
            $originalName = pathinfo($image->getClientOriginalName(), PATHINFO_FILENAME);
            $safeName = Str::slug($originalName);
            $extension = $image->getClientOriginalExtension();
            $filename = time() . '_' . $safeName . '.' . $extension;
             $path = $request->file('photo')->storeAs('public/uploads',$filename);
            $user->photo_url = $path;
            // $user->photo_url = $filename;
        }

        $user->updated_at = date('Y-m-d H:i:s');
        $user->updated_by = Session::get('user_id');
        $user->save();
        return apiResponse('success', 'Member updated successfully!', null);
    }
    public function edit($id)
    {
        $user = Member::where('member_id', $id)->first();
        $districts = District::all();
        $blocks = Block::where('district_id', $user->district_id)->get();

        return view('admin.member')->with(['user'=> $user, 'districts' => $districts, 'blocks' => $blocks]);
    }


    // Delete record
    public function delete($id)
    {
        $user = User::findOrFail($id);
        $user->delete();
        return redirect()->route('cm.index')->with('success', 'CM deleted successfully!');
    }

    public function uploadCm(Request $request)
    {

    }


    public function import(Request $request)
    {
        $request->validate([
            'member_file' => 'required|mimes:csv,txt|max:2048',
        ]);


        $file = $request->file('member_file');
        $path = $file->getRealPath();


        // Read CSV file
        $rows = array_map('str_getcsv', file($path));
        $header = array_map('trim', $rows[0]);
        unset($rows[0]); // remove header row

        DB::beginTransaction();
        try {
            foreach ($rows as $row) {
                $data = array_combine($header, $row);

                Member::create([
                    'member_name'  => $data['member_name'] ?? null,
                    'member_sh_id' => $data['member_sh_id'] ?? null,
                    'father_name'  => $data['father_name'] ?? null,
                    'member_email' => $data['member_email'] ?? null,
                    'member_phone' => $data['member_phone'] ?? null,
                    'status'       => $data['status'] ?? 1,
                    'dob'          => $data['dob'] ?? null,
                    'doj'          => $data['doj'] ?? null,
                    'designation'  => $data['designation'] ?? null,
                    'panchayat'    => $data['panchayat'] ?? null,
                    'address'      => $data['address'] ?? null,
                    'jivika_name'  => $data['jivika_name'] ?? null,
                    'photo_url'    => $data['photo_url'] ?? null,
                    'district_id'  => $data['district_id'] ?? 0,
                    'block_id'     => $data['block_id'] ?? 0,
                    'shg_id'       => $data['shg_id'] ?? null,
                    'user_type'    => $data['user_type'] ?? 'MEMBER',
                    'created_by'   => auth()->id() ?? 1,
                    'report_to'    => $data['report_to'] ?? null,
                    'created_at'   => now(),
                    'updated_at'   => now(),
                ]);
            }
            DB::commit();

            return back()->with('success', 'Members imported successfully.');
        } catch (\Exception $e) {
            DB::rollBack();
            $message = $e->getMessage();

            // Remove the SQL query part (everything after "(SQL:")
            if (strpos($message, '(SQL:') !== false) {
                $message = substr($message, 0, strpos($message, '(SQL:'));
            }

            return back()->with('error', 'Import failed: ' .  trim($message));
        }
    }


    public function downloadSample()
    {
        $headers = [
            'Content-Type' => 'text/csv',
            'Content-Disposition' => 'attachment; filename="member_sample.csv"',
        ];

        $columns = [
            'member_name', 'member_sh_id', 'father_name', 'member_email',
            'member_phone', 'status', 'dob', 'doj', 'designation', 'panchayat',
            'address', 'jivika_name', 'photo_url', 'district_id', 'block_id',
            'shg_id', 'user_type', 'report_to'
        ];

        $callback = function() use ($columns) {
            $file = fopen('php://output', 'w');
            // Write header
            fputcsv($file, $columns);

            // Add example row
            fputcsv($file, [
                'Manish Kumar', 'SH123', 'Ram Kumar', 'manish@example.com', '9876543210',
                '1', '1995-02-10', '2024-05-12', 'President', 'ABC Panchayat',
                '123 Main Street', 'Jivika A', 'photos/1731051600_manish.jpg',
                '1', '2', 'SHG1', 'MEMBER', '3'
            ]);

            fclose($file);
        };

        return new StreamedResponse($callback, 200, $headers);
    }

}
