<?php

namespace App\Modules\Workflow;

use Illuminate\Support\Facades\Request;
use Illuminate\Support\Facades\Response;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\BaseController;

class ScheduledEmailControllerREST extends BaseController
{
    /**
     * Display a listing of the resource.
     *
     * @return Response
     */
    public function index()
    {
        $query = DB::table('scheduled_emails')
            ->select('scheduled_emails.*')
            ->orderBy('scheduled_emails.send_on', 'desc');

        $query = $query->paginate(request()->get('limit', 20));

        $response = [
            'success'      => true,
            'data'         => $query->getCollection()->toArray(),
            'total'        => $query->total(),
            'current_page' => $query->currentPage(),
            'last_page'    => $query->lastPage(),
        ];

        return Response::json($response);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @return Response
     */
    public function store()
    {
        $data = request()->all();
        
        $emailId = DB::table('scheduled_emails')->insertGetId([
            'to' => $data['to'],
            'subject' => $data['subject'],
            'body' => $data['body'],
            'send_on' => $data['send_on'],
            'status' => $data['status'] ?? 'pending',
            'created_at' => now(),
            'updated_at' => now(),
        ]);

        return Response::json(['success' => true, 'email_id' => $emailId]);
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return Response
     */
    public function show($id)
    {
        $email = DB::table('scheduled_emails')->where('id', $id)->first();

        if (!$email) {
            return Response::json(['error' => 'Scheduled email not found'], 404);
        }

        return Response::json($email);
    }
}
