<?php
defined(page_security_key) or exit;

$page = 'dealer_manage';
//Check if allowed
if (isAllowed($page,$_SESSION['profile'],$_SESSION['permission'],'R') === 0){
    header('location: index.php');
    exit;
}
//PAGE Security
$update_allowed = isAllowed($page ,$_SESSION['profile'],$_SESSION['permission'],'U');
$delete_allowed = isAllowed($page ,$_SESSION['profile'],$_SESSION['permission'],'D');
$create_allowed = isAllowed($page ,$_SESSION['profile'],$_SESSION['permission'],'C');


if (isset($_GET['rowID']) && $_GET['rowID'] !=''){
    $url = 'index.php?page=dealer&rowID='.$_GET['rowID'];
} else {
    $url = 'index.php?page=dealers';
}

// Default input dealer values
$responses = [
    'rowID' => '',
    'name' => '',
    'status' => '',
    'usp1' => '',
    'usp2' => '',
    'usp3' => '',
    'short_description' => '',
    'long_description' => '',
    'address' => '',
    'postalcode' => '',
    'city' => '',
    'state' => '',
    'country' => '',
    'email' => '',
    'phone' => '',
    'opening_hours' => [
        1 => ['start' => '09:00', 'end' => '17:00'], // Monday
        2 => ['start' => '09:00', 'end' => '17:00'], // Tuesday
        3 => ['start' => '09:00', 'end' => '17:00'], // Wednesday
        4 => ['start' => '09:00', 'end' => '17:00'], // Thursday
        5 => ['start' => '09:00', 'end' => '17:00'], // Friday
        6 => ['start' => '09:00', 'end' => '20:00'], // Saturday
        7 => null // Sunday - Closed
    ],
    'lat' => '',
    'lng' => '',
    'url' => '',
    'rating_overall' => '',
    'rating_website' => '',
    'garden_center' => '',
    'brand_type' => '',
    'showroom_size' => '',
    'locations' => '',
    'focus_offering' => '',
    'dealer_type' => '',
    'dealer_slug' => '',
    'dealer_media' => '',
    'full_path' =>'',
    'created' => '',
    'createdby' => $_SESSION['username'],
    'updated' => '',
    'updatedby' => ''
];

if (isset($_GET['rowID'])) {
    // ID param exists, edit an existing dealer

    //CALL TO API
    $api_url = '/v2/dealers/rowID='.$_GET['rowID'];
    $responses = ioServer($api_url,'');
    //Decode Payload
    if (!empty($responses)){$responses = json_decode($responses,true);}else{$responses = null;}
    $responses = $responses[0];
    
    //CALL TO MEDIA API
    $api_url = '/v2/media/list=dealer_image';
    $media_responses = ioServer($api_url,'');

    //Decode Payload
    if (!empty($media_responses)){$media_responses = json_decode($media_responses,true);}else{$media_responses = null;}

    if ($update_allowed === 1){
        
        
        if (isset($_POST['submit'])) {
            
            //GET ALL POST DATA
            $payload = json_encode($_POST, JSON_UNESCAPED_UNICODE);
            //API call
            $responses = ioServer('/v2/dealers', $payload);
            if ($responses === 'NOK'){

            } else {
                header('Location: index.php?page=dealer&rowID='.$_GET['rowID'].'&success_msg=2');
                exit;
            
            }
        }
    }
    
    if ($delete_allowed === 1){
        if (isset($_POST['delete'])) {
            //GET ALL POST DATA
            $payload = json_encode($_POST, JSON_UNESCAPED_UNICODE);
            //API call
            $responses = ioServer('/v2/dealers', $payload);
            if ($responses === 'NOK'){

            } else {
            // Redirect and delete dealer
            header('Location: index.php?page=dealers&success_msg=3');
            exit;
            }
        }
    }
   
} else {
    // Create a new dealer
    if (isset($_POST['submit']) && $create_allowed === 1) {

        //GET ALL POST DATA
        $payload = json_encode($_POST , JSON_UNESCAPED_UNICODE);
        //API call
        $responses = ioServer('/v2/dealers', $payload);
        if ($responses === 'NOK'){

            } 
        else {
            header('Location: index.php?page=dealers&success_msg=1');
            exit;
        }
    }
}

template_header('Dealer', 'dealer', 'manage');

$view ='
<form action="" method="post">
    <div class="content-title responsive-flex-wrap responsive-pad-bot-3">
        <h2 class="responsive-width-100">'.($dealers_h2 ?? 'Dealer').' '.$responses['name'].'</h2>
        <a href="'.$url.'" class="btn alt mar-right-2">'.$button_cancel.'</a>
';

if ($delete_allowed === 1){
    $view .= '<input type="submit" name="delete" value="Delete" class="btn red mar-right-2" onclick="return confirm(\'Are you sure you want to delete this dealer?\')">';
}
if ($update_allowed === 1){
    $view .= '<input type="submit" name="submit" value="Save" class="btn">';
}
   
$view .= '</div>';

$view .= '<div class="tabs">
            <a href="#" class="active">'.($view_dealers_information ?? 'Dealer information').'</a>
            <a href="#">'.($view_dealer_details_1 ?? 'Descriptions').'</a>
            <a href="#">'.($view_dealer_details_3 ?? 'Location').'</a>
            <a href="#">'.($dealers_openinghours ?? 'opening_hours').'</a>
            <a href="#">'.($view_dealer_details_2 ?? 'Settings').'</a>
            <a href="#">'.$tab3.'</a>
         </div>
    ';

$view .= '<div class="content-block tab-content active">
            <div class="form responsive-width-100">
                <label for="status">'.$dealers_status.'</label>
                <select id="status" name="status">
                    <option value="1" '.($responses['status']==1?' selected':'').'>'.$general_status_1 .'</option>
                    <option value="0" '.($responses['status']==0?' selected':'').'>'.$general_status_0 .'</option>
                </select>
            </div>
            <div class="form responsive-width-100">
                <label for="dealername"><i class="required">*</i>'.$dealers_name.'</label>
                <input id="name" type="text" name="name" placeholder="'.$dealers_name.'" value="'.$responses['name'].'" required>
            </div>
            <div class="form responsive-width-100">
                <label for=""><i class="required">*</i>'.($dealers_slug ?? 'dealer_slug').'</label>
                <input id="name" type="text" name="dealer_slug" placeholder="'.($dealers_slug ?? 'dealer_slug').'" value="'.$responses['dealer_slug'].'">
            </div>
            <div class="form responsive-width-100">
                <input id="source_'.$responses['rowID'].'" type="hidden" name="dealer_media" value="'.$responses['dealer_media'].'">
                    <img id="image_'.$responses['rowID'].'" src="'.$responses['full_path'].'" alt="" style="display: block; max-width: 75px;">
                <button type="button" class="btn" id="openSelectorBtn" onclick="setSourceID(\''.$responses['rowID'].'\'), openDialog(\'image_'.$responses['rowID'].'\')">'.($button_assign_image ?? 'Assign Image').'</button>   
            </div>
        </div>';

        if (isset($_GET['rowID'])){
            $view .= '<input type="hidden" name="rowID" value="'.(encodeUuid($responses['rowID']) ?? '').'">';
        }

$view .= '<div class="content-block tab-content">
            <div class="form responsive-width-100">
                <label for="dealerdescription">'.($dealers_short_description ?? 'short').'</label>
                <textarea id="description" name="short_description" placeholder="'.($dealers_short_description ?? 'short').'">'.$responses['short_description'].'</textarea>
            </div>
            <div class="form responsive-width-100">
                <label for="dealerdescription">'.($dealers_long_description ?? 'long').'</label>
                <textarea id="description" name="long_description" placeholder="'.($dealers_long_description ?? 'long').'">'.$responses['long_description'].'</textarea>
            </div>
            <div class="form responsive-width-100">
                <label for="dealerdescription">'.($dealers_usp1 ?? 'usp').'</label>
                <textarea id="description" name="usp1" placeholder="'.($dealers_usp1 ?? 'usp').'">'.$responses['usp1'].'</textarea>
            </div>
             <div class="form responsive-width-100">
                <label for="dealerdescription">'.($dealers_usp2 ?? 'usp').'</label>
                <textarea id="description" name="usp2" placeholder="'.($dealers_usp2 ?? 'usp').'">'.$responses['usp2'].'</textarea>
            </div>
             <div class="form responsive-width-100">
                <label for="dealerdescription">'.($dealers_usp3 ?? 'usp').'</label>
                <textarea id="description" name="usp3" placeholder="'.($dealers_usp3 ?? 'usp').'">'.$responses['usp3'].'</textarea>
            </div>
        </div>';       

$view .= '<div class="content-block tab-content">
            <div class="form responsive-width-100">
                <label for="">'.($dealers_address ?? 'address').'</label>
                <input name="address" type="text" value="'.$responses['address'].'">
            </div>
            <div class="form responsive-width-100">
                <label for="">'.($dealers_postalcode ?? 'postalcode').'</label>
                <input name="postalcode" type="text" value="'.$responses['postalcode'].'">
            </div>
            <div class="form responsive-width-100">
                <label for="">'.($dealers_city ?? 'city').'</label>
                <input name="city" type="text" value="'.$responses['city'].'" required>
            </div>
            <div class="form responsive-width-100">
                <label for="">'.($dealers_state ?? 'state').'</label>
                <input name="state" type="text" value="'.$responses['state'].'">
            </div>
            <div class="form responsive-width-100">
                <label for="">'.($dealers_country ?? 'country').'</label>
                <input name="country" type="text" value="'.$responses['country'].'">
            </div>
            <div class="form responsive-width-100">
                <label for="">'.($dealers_email ?? 'email').'</label>
                <input name="email" type="text" value="'.$responses['email'].'">
            </div>
             <div class="form responsive-width-100">
                <label for="">'.($dealers_phone ?? 'phone').'</label>
                <input name="phone" type="text" value="'.$responses['phone'].'">
            </div>
            <div class="form responsive-width-100">
                <label for="">'.($dealers_url ?? 'url').'</label>
                <input name="url" type="text" value="'.$responses['url'].'">
            </div>
            <div class="form responsive-width-100">
                <label for="">'.($dealers_lat.' - '.$dealers_lng ?? 'geolocation').'</label>
                <input name="lat" type="text" value="'.$responses['lat'].'">
                <input name="lng" type="text" value="'.$responses['lng'].'">
            </div>
        </div>';

$view .= '<div class="content-block tab-content">
            <div class="form responsive-width-100">
                <table>';

                $opening_hours = is_string($responses['opening_hours']) ? json_decode($responses['opening_hours'],true) : $responses['opening_hours'];
                foreach ($opening_hours as $day => $value){
                $view .= '<tr>
                            <td style="width:25%;">'.(${'general_day_'.$day} ?? 'Not specified').'</td>
                            <td>
                                '.($general_from ?? 'From').' <input type="time" id="start_'.$day.'" name="'.(isset($value['start']) ? 'opening_hours['.$day.'][start]' : '').'" value="'.(isset($value['start']) ? $value['start'] : '09:00').'" '.(isset($value['start']) ? '' : 'disabled').'>
                                '.($general_from ?? 'To').' <input type="time" id="end_'.$day.'" name="'.(isset($value['end']) ? 'opening_hours['.$day.'][end]' : '').'" value="'.(isset($value['end']) ? $value['end'] : '18:00').'" '.(isset($value['end']) ? '' : 'disabled').'>
                            </td>
                            <td>
                                '.($general_closed ?? 'Closed').'<input type="checkbox" id="closed_'.$day.'" onchange="toggleClosed('.$day.')" '.(isset($value['end']) ? '' : 'checked').'>
                                '.(isset($value['end']) ? '' : '<input type="hidden" id="null_'.$day.'" name="opening_hours['.$day.']" value="null">').'
                            </td>

                        </tr>';
                }
$view .='
                </table>
            </div>
        </div>';

$view .= '
    <div class="content-block tab-content">
        <div class="form responsive-width-100">
            <label for="status">'.($dealers_garden_center ?? 'Garden_center').'</label>
            <select id="status" name="garden_center">
                <option value="1" '.($responses['garden_center']==1?' selected':'').'>'.$general_yes .'</option>
                <option value="0" '.($responses['garden_center']==0?' selected':'').'>'.$general_no .'</option>
            </select>
        </div>
        <div class="form responsive-width-100">
            <label for="status">'.($dealers_brand_type ?? 'Brand_type').'</label>
            <select id="status" name="brand_type">
                <option value="0" '.($responses['brand_type']==0?' selected':'').'>'.$brand_type_0.'</option>
                <option value="1" '.($responses['brand_type']==1?' selected':'').'>'.$brand_type_1.'</option>
            </select>
        </div>
        <div class="form responsive-width-100">
            <label for="status">'.($dealers_showroom_size ?? 'Showroom_size').'</label>
            <select id="status" name="showroom_size">
                <option value="0" '.($responses['showroom_size']==0?' selected':'').'>'.$showroom_size_0.'</option>
                <option value="1" '.($responses['showroom_size']==1?' selected':'').'>'.$showroom_size_1.'</option>
                <option value="2" '.($responses['showroom_size']==2?' selected':'').'>'.$showroom_size_2.'</option>
            </select>
        </div>
         <div class="form responsive-width-100">
            <label for="status">'.($dealers_focus_offering ?? 'focus_offering').'</label>
            <select id="status" name="focus_offering">
                <option value="0" '.($responses['focus_offering']==0?' selected':'').'>'.$focus_offering_0.'</option>
                <option value="1" '.($responses['focus_offering']==1?' selected':'').'>'.$focus_offering_1.'</option>
            </select>
        </div>
        <div class="form responsive-width-100">
            <label for="status">'.($dealers_type ?? 'dealer_type').'</label>
            <select id="status" name="dealer_type">
                <option value="0" '.($responses['dealer_type']==0?' selected':'').'>'.$dealer_type_0.'</option>
                <option value="1" '.($responses['dealer_type']==1?' selected':'').'>'.$dealer_type_1.'</option>
                <option value="2" '.($responses['dealer_type']==2?' selected':'').'>'.$dealer_type_2.'</option>
            </select>
        </div>
        <div class="form responsive-width-100">
            <label for="status">'.($dealers_locations ?? 'dealer_locations').'</label>
            <select id="status" name="locations">
                <option value="1" '.($responses['locations']==1?' selected':'').'>'.$general_yes .'</option>
                <option value="0" '.($responses['locations']==0?' selected':'').'>'.$general_no .'</option>
            </select>
        </div>
    </div>';

$view .= '<div class="content-block tab-content">
        <div class="form responsive-width-100">
            <label for="dealercode">'.$general_created.'</label>
            <input id="name" type="text" name="" placeholder="'.$general_created.'" value="'.$responses['created'].'" readonly>
            <label for="dealercode">'.$general_createdby.'</label>
            <input id="name" type="text" name="" placeholder="'.$general_createdby.'" value="'.$responses['createdby'].'" readonly>
            <label for="dealercode">'.$general_updated.'</label>
            <input id="name" type="text" name="" placeholder="'.$general_updated.'" value="'.$responses['updated'].'" readonly>
            <label for="dealercode">'.$general_updatedby.'</label>
            <input id="name" type="text" name="" placeholder="'.$general_updatedby.'" value="'.$responses['updatedby'].'" readonly>';

            if (isset($responses['url']) && $responses['url'] !=''){

                $view .= '<a href="index.php?page=media_scanner&domain='.$responses['url'].'&rowID='.encodeUuid($responses['rowID']).'" class="btn">'.($button_media_scanner ?? 'media_scanner').'</a>';
            }
$view .= '
        </div>
    </div>';
$view .= '</form>';

$view .= '<!-- Image Selector Dialog -->
            <dialog id="imageSelector" style="padding: 20px; max-width: 800px;">
                <h3>Select an Image</h3>
                <div style="display: grid; grid-template-columns: repeat(5, 1fr); gap: 10px; margin: 20px 0;">';

            if (isset($media_responses) && is_array($media_responses)){
                foreach ($media_responses as $media_response){
                    $view .= '
                        <img src="'.$media_response['full_path'].'" id="'.$media_response['rowID'].'" title="'.$media_response['title'].'" alt="'.$media_response['title'].'" style="width: 100%; cursor: pointer; border: 2px solid transparent;" onmouseover="this.style.border=\'2px solid #4CAF50\'" onmouseout="this.style.border=\'2px solid transparent\'" onclick="selectImage(this.id,this.src)">
                    ';
                }
            }
$view .= '</div>
            <button onclick="closeImageSelector()">Close</button>
            </dialog>
';


$view .= '<script>
            //POPUP FOR IMAGE SELECTION
            const dialog = document.getElementById(\'imageSelector\');
            image_source_id = 0;
            //const openButton = document.getElementById(\'openSelectorBtn\');

            function setSourceID(sourceid){
                image_source_id = "source_"+sourceid;
                image_source_src = "image_"+sourceid;
            }

            function openDialog(){
                dialog.showModal();
            }

            function selectImage(id,src) {

                if (image_source_id != 0){
                    const selectedImageInput = document.getElementById(image_source_id);   
                    const previewImage = document.getElementById(image_source_src);
                    
                    selectedImageInput.value = id;
                    previewImage.src = src;
          
                }
                else {
                    const selectedImageInput = document.getElementById(\'selectedImage\');
                    const previewImage = document.getElementById(\'previewImage\');

                    selectedImageInput.value = id;
                    previewImage.src = src;
                    previewImage.style.display = \'block\';
                }         
               
                dialog.close();
            }

            function closeImageSelector() {
                dialog.close();
            }

        </script>';

//Output
echo $view;
template_footer()?>