<?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 App\Models\SeoKeywordUrlRel; // 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 AnalyticKeywordController  extends Controller
{
    protected $table = 'seo_keyword';

    public function showKeywordsForm()
    {
        if (!Auth::check()) {
            return redirect(localized_route('login')); // Redirect to login if not authenticated
        }
        $userProfile = Auth::user();
        // Get website list from websites only status_flg is A 
        $websitesList = Websites::getAllWebsiteByUser($userProfile->id, null, null, null);
        //
        ///////////////////////////////////
        $keywordList = DB::table('seo_keyword as keyword')
            ->where('keyword.accountCode', $userProfile->accountCode)
            ->select('keyword.*')
            ->get();
        
        $websitRelList = array();
        foreach( $keywordList as $indexKeywordList=>$keywordListInfo ){
            $websitRelList = DB::table('websites')
            ->leftJoin('seo_keyword_url_rel as keywordUrlRel', 'websites.websiteCode', '=', 'keywordUrlRel.seoWebsiteCode')
            ->where('keywordUrlRel.seoKeywordID', $keywordListInfo->seoKeywordID)
            ->select('websites.*', 'keywordUrlRel.*')
            ->get();

            if( $websitRelList ){
                $keywordListInfo->websiteRel = $websitRelList;
            }else{
                $keywordListInfo->websiteRel = null;
            }
        }
            
        return view('dashboard.analytic.keywords', compact('userProfile', 'websitesList', 'keywordList', 'websitRelList'));
    }
    
    public function showUpdateKeywordForm(Request $request)
    {
        if (!Auth::check()) {
            return redirect(localized_route('login')); // Redirect to login if not authenticated
        }
        $userProfile = Auth::user();
        $userRole = Groups::getPermissionRole($userProfile->groupId);
        ///
        $seoKeywordID = $request->keyword;
        $seoUrlRel = SeoKeywordUrlRel::GetWebUrlRelByAccountCode($userProfile->accountCode, $seoKeywordID);
        $editKeywordInfo = SeoKeyword::selectKeywordList($request, $seoKeywordID);

        // Get website list from websites only status_flg is A 
        $websitesList = Websites::getAllWebsiteByUser($userProfile->id, null, null, null);
        //
        ///////////////////////////////////
        $keywordList = DB::table('seo_keyword as keyword')
            ->where('keyword.accountCode', $userProfile->accountCode)
            ->select('keyword.*')
            ->get();
        
        $websitRelList = array();
        foreach( $keywordList as $indexKeywordList=>$keywordListInfo ){
            $websitRelList = DB::table('websites')
            ->leftJoin('seo_keyword_url_rel as keywordUrlRel', 'websites.websiteCode', '=', 'keywordUrlRel.seoWebsiteCode')
            ->where('keywordUrlRel.seoKeywordID', $keywordListInfo->seoKeywordID)
            ->select('websites.*', 'keywordUrlRel.*')
            ->get();

            if( $websitRelList ){
                $keywordListInfo->websiteRel = $websitRelList;
            }else{
                $keywordListInfo->websiteRel = null;
            }
        }
            
            
        return view('dashboard.analytic.keywordUpdate', compact('userProfile', 'websitesList', 'editKeywordInfo', 'keywordList', 'userRole', 'seoUrlRel', 'websitRelList'));
    }//end showUpdateWebsiteForm
    
    public function deleteKeyword(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 = SeoKeyword::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.keywordDelete', compact('userProfile', 'websitesList'));
    }//end showUpdateWebsiteForm
    
    public function GetKeywordByInput($seoKeywordTxt=null)
    {
        
    }
    
    public function SaveKeywords(Request $request)
    {
        if (!Auth::check()) {
            return redirect(localized_route('login')); // Redirect to login if not authenticated
        }
        $userProfile = Auth::user();

        //validate Keyword formail
        $validator = Validator::make($request->all(), 
        [
            'seoKeywordtxt' => 
            [
                'bail',
                'required',
                //'unique:seo_keyword,seoKeywordtxt',//unique to check already exists then fail validate.
                //'exists:seo_keyword,seoKeywordtxt', // exists use to check already exists then pass validate.
            ],
            'websiteList' => 'required|array|min:1',// must be an array and have at least 1 item
            //'websiteList.*' => 'exists:seo_keyword_url_rel,seoWebsiteCode',// optional: each item must exist in DB
        ],
        [
            'seoKeywordtxt.required' => 'Please input keyword.',
            //'seoKeywordtxt.unique'   =>   'This keyword "'.$request->seoKeywordtxt.'" already exists. Please choose one from the list or enter a different keyword.',
            'websiteList.required' => 'Please pick at least one domain to continue.',
        ]);

        if ($validator->fails()) {
            return redirect()->back()
                             ->withErrors($validator)
                             ->withInput();
        }
//dd($request);
        //save to db;
        $seoKeywordID = "";
        if($request->mode===null){//add new keyword
            $seoKeywordID = generateValidationCode();
            $seoKeywordInfo = SeoKeyword::where('seoKeywordtxt', $request->seoKeywordtxt)->first();
            if ($seoKeywordInfo) {
                // exists in DB
                $seoKeywordID = $seoKeywordInfo->seoKeywordID;
            } else {
                // Does not exist
                $accountCodeAdd = $userProfile->accountCode;
                SeoKeyword::create([
                    'seoKeywordID' => $seoKeywordID,
                    'seoKeywordtxt' => $request->seoKeywordtxt,
                    'accountCode' => $accountCodeAdd,
                    'status_flg' => 'A',
                    'automatic_tracking_status' => 'I',
                    'timeCreated' => now(),
                    'timeAccessed' => now(),
                    'created_by' => $userProfile->id
                ]);
            }
        }else if($request->mode==='update'){

            $seoKeywordID       = $request->seoKeywordID;
            SeoKeyword::where('seoKeywordID', $request->seoKeywordID)
                       ->update([
                            'seoKeywordtxt' => $request->seoKeywordtxt,
                            'accountCode' => $userProfile->accountCode,
                            'updated_at' => now(),
                            'updated_by' => $userProfile->id
                            //'timeAccessed' => now(),
                            //'status_flg' => $status_flg,
                            //'automatic_tracking_status' => $automatic_tracking_status,
                       ]);
            
        }

        /////// manage keyword-website rel
        $this->SaveWebsiteKeywordRel($request, $userProfile, $seoKeywordID);
        ////////////////////////////////////
        $keywordList = DB::table('seo_keyword_url_rel as keywordUrlRel')
            ->join('seo_keyword as keyword', 'keywordUrlRel.seoKeywordID', '=', 'keyword.seoKeywordID')
            ->join('websites as website', 'keywordUrlRel.seoWebsiteCode', '=', 'website.websiteCode')
            ->where('keywordUrlRel.accountCode', $userProfile->accountCode)
            ->select('*', 'keywordUrlRel.automatic_tracking_status AS keyword_automatic_tracking_status', 'keyword.created_at AS keyword_created_at', 'keyword.updated_at AS keyword_updated_at', 'keywordUrlRel.status_flg AS keyword_status_flg')
            ->get();
        ///////////////////////////

        // Get website list from websites seo_url_register 
        $websitesList = Websites::getAllWebsite($userProfile->id);
        return view('dashboard.analytic.keywords', compact('userProfile', 'websitesList', 'keywordList'));
    }
    
    public function SaveUserWebsiteKeywordRel($request, $userProfile, $keywordID=null)
    {
        // Tags to delete (in DB but not checked anymore)
        DB::table('seo_keyword_url_rel')
            ->where('seoKeywordID', $keywordID)
            ->where('accountCode', $userProfile->accountCode)
            ->delete();

        $checkedWebsites = $request->input('websiteList', []); // All selected checkboxes (array of websiteList)
        // Get current DB tag IDs
        $existingWebsites = DB::table('seo_keyword_url_rel')
            ->where('seoKeywordID', $keywordID)
            ->pluck('seoWebsiteCode')
            ->toArray();

        // Tags to insert (checked but not in DB)
        $seoWebsiteCode = "";
        $toInsert = array_diff($checkedWebsites, $existingWebsites); 
        if(count($existingWebsites) > 0){
            $seoWebsiteCode = $existingWebsites[0];
        }

dd($checkedWebsites);
        foreach ($checkedWebsites as $domain) {
            $seoKeywordUrlRelID = generateValidationCode();
            DB::table('seo_keyword_url_rel')->insert([ 
                'seoKeywordUrlRelID' => $seoKeywordUrlRelID,
                'seoKeywordID' => $keywordID,
                'seoWebsiteCode' => Websites::getWebsiteCodeByDomain($domain),
                'seoRelFlg' => 'A',
                'accountCode' => $userProfile->accountCode,
                'created_at' => now(),
                'created_by' => $userProfile->id,
                'updated_at' => now(),
                'updated_by' => $userProfile->id,
            ]);
        }

        return true;
    }//SaveWebsiteKeywordRel

}//end class AnalyticKeywordController
