<?php
namespace App\Http\Controllers;

use Illuminate\Support\Facades\Auth;
use App\Models\Accounts; // Use the Account model
use App\Models\Groups; // Use the Group model
use App\Models\Activity; // Use the Activity model
use Illuminate\Http\Request;
use App\Models\GCategory; 
use App\Models\GCategoryType; 
use App\Models\GContent;
use App\Models\SEOTools; // Use the SEOTools model
use App\Models\History; // Use the History model
use App\Models\Websites; // Use the Websites model
use App\Models\SeoKeyword; // Use the SeoKeyword model
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;//validate form input format

use Illuminate\Support\Facades\View;
/**
 * Description of DashboardController
 *
 * @author Phattharaphon
 */

class AnalyticWebsiteController extends Controller
{
    public function showWebsitesForm()
    {
        if (!Auth::check()) {
            return redirect(localized_route('login')); // Redirect to login if not authenticated
        }
        $userProfile = Auth::user();
        $userRole = Groups::getPermissionRole($userProfile->groupId);
        // Get website list from websites seo_url_register 
        $websitesList = Websites::getAllWebsite($userProfile->id, null, null,  json_encode($userRole));

        return view('dashboard.analytic.websites', compact('userProfile', 'websitesList', 'userRole'));
    }
    
    public function showUpdateWebsiteForm(Request $request)
    {
        if (!Auth::check()) {
            return redirect(localized_route('login')); // Redirect to login if not authenticated
        }
        $userProfile = Auth::user();
        $userRole = Groups::getPermissionRole($userProfile->groupId);

        $editWebsiteInfo = Websites::getAllWebsite($userProfile->id, $request->domain, null,json_encode($userRole));

        // Get website list from websites seo_url_register 
        $websitesList = Websites::getAllWebsite($userProfile->id, null, null,  json_encode($userRole));
        return view('dashboard.analytic.websiteUpdate', compact('userProfile', 'websitesList', 'editWebsiteInfo', 'userRole'));
    }//end showUpdateWebsiteForm
    
    public function deleteWebsite(Request $request)
    {
        if (!Auth::check()) {
            return redirect(localized_route('login')); // Redirect to login if not authenticated
        }
        $userProfile = Auth::user();
        $userRole = Groups::getPermissionRole($userProfile->groupId);        
        
        $deleteWebsiteInfo = Websites::deleteWebsite($request->websiteId, $userProfile->id, $request->domain);

        if(!$deleteWebsiteInfo){
            return redirect()->back()->withErrors(['error' => 'Error!! Delete domain failed.']);
        }
        // Get website list from websites seo_url_register 
        $websitesList = Websites::getAllWebsite($userProfile->id, null, null,  json_encode($userRole));
        return view('dashboard.analytic.websiteDelete', compact('userProfile', 'websitesList'));
    }//end showUpdateWebsiteForm
    
    public function SaveWebsites(Request $request, $websiteId=null)
    {
        if (!Auth::check()) {
            return redirect(localized_route('login')); // Redirect to login if not authenticated
        }
        $userProfile = Auth::user();

        //validate domain formail
        $validator = Validator::make($request->all(), [
            'domain' => [
                'bail',
                'required',
                'regex:/^(?!https?:\/\/)(?!www\.)[a-z0-9-]+(\.[a-z]{2,})+$/i'            
            ],
        ], [
            'domain.regex' => 'The website must be a valid domain like "example.com" without http://, https:// or www.'
        ]);

        if ($validator->fails()) {
            return redirect()->back()
                             ->withErrors($validator)
                             ->withInput();
        }
        //save to db;
        $websiteCode = "";//define websiteCode
        if($request->mode===null){//add new website
            $websiteCode = generateValidationCode();//generate websiteCode
//dd($websiteCode);
            Websites::create([
                'userId' => $userProfile->id,
                'domain' => $request->domain,
                'websiteCode' => $websiteCode,
                'status_flg' => "A",
                'automatic_tracking_status' => "I",
                'timeCreated' => now(),
                'timeAccessed' => now()
            ]);
        }else if($request->mode==='update'){
            $websiteInfoUpdate = Websites::getAllWebsite($userProfile->id, $request->domain, $request->websiteId);
            $automatic_tracking_status = $websiteInfoUpdate->automatic_tracking_status;
            if(!$automatic_tracking_status){
                $automatic_tracking_status = "I";
            }
            
            $status_flg = $websiteInfoUpdate->status_flg;
            if(!$status_flg){
                $status_flg = "I";
            }
            //
            $websiteCode = $websiteInfoUpdate->websiteCode;
            if($websiteCode === "" || $websiteCode === null){
                $websiteCode = generateValidationCode();                
            }

            Websites::where('id', $request->websiteId)
                   ->update([
                        'websiteCode' => $websiteCode,
                        'domain' => $request->domain,
                        'timeAccessed' => now(),
                        'status_flg' => $status_flg,
                        'automatic_tracking_status' => $automatic_tracking_status,
                   ]);
            
        }
        
        // Get website list from websites seo_url_register 
        $websitesList = Websites::getAllWebsite($userProfile->id);
        return view('dashboard.analytic.websites', compact('userProfile', 'websitesList'));
    }//end savewebsite
    
}//end class AnalyticWebsiteController
