<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Project;
use Illuminate\Support\Facades\Response;

class ProjectController extends Controller
{
    /** GET /api/get-projects */
    public function index()
    {
        $projects = Project::orderBy('id', 'desc')->get();

        return response()->json(['success' => true, 'data' => $projects]);
    }

    /** POST /api/add-project  (multipart/form-data — includes optional brochure file) */
    public function store(Request $request)
    {
        $brochureUrl = '';

        if ($request->hasFile('brochure') && $request->file('brochure')->isValid()) {
            $file     = $request->file('brochure');
            $fileName = time() . '_' . $file->getClientOriginalName();
            // Store in public/uploads/brochures — accessible via /uploads/brochures/<file>
            $file->move(public_path('uploads/brochures'), $fileName);
            $brochureUrl = url('uploads/brochures/' . $fileName);
        }

        $project = Project::create([
            'project_name'     => $request->input('project_name', ''),
            'location'         => $request->input('location', ''),
            'builder_name'     => $request->input('builder_name', ''),
            'flat_type'        => $request->input('flat_type', ''),
            'carpet_area'      => $request->input('carpet_area', ''),
            'price_range'      => $request->input('price_range', ''),
            'possession_date'  => $request->input('possession_date', ''),
            'amenities'        => $request->input('amenities', ''),
            'description'      => $request->input('description', ''),
            'drive_folder_link'=> $request->input('drive_folder_link', ''),
            'brochure_url'     => $brochureUrl,
            'status'           => 'Active',
        ]);

        return response()->json(['success' => true, 'message' => 'Project added successfully', 'id' => $project->id]);
    }

    /** POST /api/delete-project  (JSON body: { id }) */
    public function destroy(Request $request)
    {
        // Brokers are not permitted to delete projects
        $role = $request->header('X-User-Role');
        if ($role === 'broker') {
            return response()->json([
                'success' => false,
                'message' => 'Permission denied'
            ], 403);
        }

        $id = $request->input('id', '');

        if ($id === '') {
            return response()->json(['success' => false, 'message' => 'Project ID missing']);
        }

        $deleted = Project::where('id', $id)->delete();

        if ($deleted) {
            return response()->json(['success' => true, 'message' => 'Project deleted successfully']);
        }

        return response()->json(['success' => false, 'message' => 'Delete failed']);
    }

    /** POST /api/update-project-status  (JSON body: { id, status }) */
    public function updateStatus(Request $request)
    {
        $id     = $request->input('id', '');
        $status = $request->input('status', '');

        if ($id === '' || $status === '') {
            return response()->json(['success' => false, 'message' => 'Missing data']);
        }

        $updated = Project::where('id', $id)->update(['status' => $status]);

        if ($updated) {
            return response()->json(['success' => true, 'message' => 'Status updated']);
        }

        return response()->json(['success' => false, 'message' => 'Update failed']);
    }

    /** GET /api/export-projects  — streams a CSV download */
    public function export()
    {
        $projects = Project::orderBy('id', 'desc')->get();

        $headers = [
            'Content-Type'        => 'text/csv; charset=UTF-8',
            'Content-Disposition' => 'attachment; filename="nestpune_projects.csv"',
        ];

        $callback = function () use ($projects) {
            $handle = fopen('php://output', 'w');

            // BOM for Excel UTF-8 compatibility
            fputs($handle, "\xEF\xBB\xBF");

            fputcsv($handle, [
                'ID', 'Project Name', 'Location', 'Builder Name',
                'Flat Type', 'Carpet Area', 'Price Range', 'Possession Date',
                'Amenities', 'Description', 'Brochure URL', 'Drive Folder Link', 'Created At',
            ]);

            foreach ($projects as $p) {
                fputcsv($handle, [
                    $p->id, $p->project_name, $p->location, $p->builder_name,
                    $p->flat_type, $p->carpet_area, $p->price_range, $p->possession_date,
                    $p->amenities, $p->description, $p->brochure_url, $p->drive_folder_link,
                    $p->created_at,
                ]);
            }

            fclose($handle);
        };

        return Response::stream($callback, 200, $headers);
    }
    public function bulkStore(Request $request)
{
    $projects = $request->input('projects');

    // If frontend sends direct array instead of { projects: [...] }
    if (!$projects && is_array($request->all())) {
        $projects = $request->all();
    }

    // If frontend sends single project object
    if (isset($projects['project_name'])) {
        $projects = [$projects];
    }

    if (!is_array($projects) || count($projects) === 0) {
        return response()->json([
            'success' => false,
            'message' => 'No projects received',
            'received' => $request->all()
        ], 422);
    }

    $inserted = 0;
    $failed = [];

    foreach ($projects as $index => $p) {
        $projectName = trim($p['project_name'] ?? '');
        $location    = trim($p['location'] ?? '');
        $status      = trim($p['status'] ?? '');

        if ($projectName === '' || $location === '' || $status === '') {
            $failed[] = [
                'row' => $index + 1,
                'project_name' => $projectName,
                'location' => $location,
                'status' => $status,
                'reason' => 'Missing required fields'
            ];
            continue;
        }

        Project::create([
            'project_name'    => $projectName,
            'location'        => $location,
            'builder_name'    => $p['builder_name'] ?? null,
            'flat_type'       => $p['flat_type'] ?? null,
            'carpet_area'     => $p['carpet_area'] ?? null,
            'price_range'     => $p['price_range'] ?? null,
            'possession_date' => $p['possession_date'] ?? null,
            'amenities'       => $p['amenities'] ?? null,
            'description'     => $p['description'] ?? null,
            'status'          => $status,
        ]);

        $inserted++;
    }

    return response()->json([
        'success' => true,
        'message' => "$inserted projects imported successfully",
        'inserted' => $inserted,
        'failed_count' => count($failed),
        'failed' => $failed
    ]);
}
}
