<?php

session_start();
ob_start();
$do = isset($_GET['do']) ? $_GET['do'] : "";
$ajaxDoArr = array("add2SimpleReturn");
include("initiateStaticSessionCommingWithCurl.php");
if (isset($_POST['curlpost']) && $_POST['curlpost'] == 1) {
    array_push($ajaxDoArr, $do);
}

if (!in_array($do, $ajaxDoArr)) {
    include("../public/impOpreation.php");
}



include_once("../public/config.php");
include("../library/newUplode/uploadfunctions.php");


require_once('../models/dao/YoutubeLinkDAO.class.php');
require_once('../models/dto/YoutubeLink.class.php');
require_once('../models/mysql/YoutubeLinkMySqlDAO.class.php');
require_once('../models/mysql/ext/YoutubeLinkMySqlExtDAO.class.php');




//get the do the action
$do = $_GET['do'];

$langs = $_SESSION['erp_lang'];
include_once("../views/languages/$langs/success.php");
include_once("../views/languages/$langs/error.php");


if (!in_array($do, $ajaxDoArr)) {
    if (isset($_POST['curlpost']) && $_POST['curlpost'] == 1) {

    } else {
        $smarty->display("header.html");
    }
}



$youtubeLink = new YoutubeLink();
$youtubeLinkDAO = new YoutubeLinkMySqlDAO();
$youtubeLinkEX = new YoutubeLinkMySqlExtDAO();

$today = date("Y-m-d");
//check and use the condition that suite this action
if (empty($do)) {
    //here the permission check
  
    $allTenders = R::findAll('tenderannouncement', "status = 'avilable' AND isdel = 0");
    $smarty->assign('allTenders', $allTenders);
    $smarty->display("memberShipsView/add.html");
} elseif ($do == "add") {
    try { 
    
        add();
        if (isset($_POST['curlpost']) && $_POST['curlpost'] == 1) {
            $data = array('status' => 1, 'message' => 'تمت العمليه بنجاح', 'message_en' => 'Success');
            echo json_encode($data);
        } else {
            header("location:?do=sucess");
        }
    } catch (Exception $e) {
        echo $e;
        die();
        if (isset($_POST['curlpost']) && $_POST['curlpost'] == 1) {
            $data = array('status' => 2, 'message' => 'حدث خطأ', 'message_en' => 'Error');
            echo json_encode($data);
        } else {
            header("location:?do=error");
        }
    }
} elseif ($do == "show") {
     
    $sql = "SELECT m.*, u.employeename 
            FROM memberships m
            LEFT JOIN user u ON m.userid = u.userid 
            WHERE m.isdel = 0 
            ORDER BY m.id DESC";
    $showData = R::getAll($sql);
   
    
    $smarty->assign('showData', $showData);

    $youtubes = $youtubeLinkDAO->queryAll();
    $smarty->assign("youtubes", $youtubes);

    $smarty->display("memberShipsView/show.html");
    $smarty->assign("customCheck", 1);
} elseif ($do == "deleteFinaly") {
    try {
        $id = (int) $_GET['id'];
        deleteFinaly($id);

        if (isset($_POST['curlpost']) && $_POST['curlpost'] == 1) {
            $data = array('status' => 1, 'message' => 'تمت العمليه بنجاح', 'message_en' => 'Success');
            echo json_encode($data);
        } else {
            header("location:?do=sucess");
        }
    } catch (Exception $e) {
        if (isset($_POST['curlpost']) && $_POST['curlpost'] == 1) {
            $data = array('status' => 2, 'message' => 'حدث خطأ', 'message_en' => 'Error');
            echo json_encode($data);
        } else {
            header("location:?do=error");
        }
    }
} elseif ($do == "edit") { //edit request
    $id = $_GET['id'];
   
    $showData = R::load('memberships', $id);
    $smarty->assign('showData', $showData);
    $smarty->display("memberShipsView/edit.html");
} elseif ($do == "update") { //edit update
    try {
        update();
        if (isset($_POST['curlpost']) && $_POST['curlpost'] == 1) {
            $data = array('status' => 1, 'message' => 'تمت العمليه بنجاح', 'message_en' => 'Success');
            echo json_encode($data);
        } else {
            header("location:?do=sucess");
        }
    } catch (Exception $e) {
        if (isset($_POST['curlpost']) && $_POST['curlpost'] == 1) {
            $data = array('status' => 2, 'message' => 'حدث خطأ', 'message_en' => 'Error');
            echo json_encode($data);
        } else {
            header("location:?do=error");
        }
    }
} elseif ($do == "sucess") {
    //here the smarty templates
    $smarty->display("succes.html");
} elseif ($do == "error") {
    //here the smarty templates
    $smarty->display("error.html");
}


$smarty->assign("customValidation", 1);

//here the global templates
if (!in_array($do, $ajaxDoArr)) {
    if (isset($_POST['curlpost']) && $_POST['curlpost'] == 1) {

    } else {
        $smarty->display("footer.html");
    }
}

/* ===============================
  function in this CONTROLLER
  ================================ */

// add in tenderannouncement tbl
function add() {
    $name = $_POST['name'];
    $phone = $_POST['phone'];
    $address = $_POST['address'];
    $etihadnum = $_POST['etihadnum'];
    $national = $_POST['national'];
    $commerce= $_POST['commerce'];
    $taax = $_POST['tax']; 
    $ettihad= $_POST['ettihad']; 
    $legal_position = $_POST['legal_position'];

    $your_img = uploadnew('yourimg', False, 0, 0, 'memberShips');
    $target_dir = "../upload/memberShips/";

    if (!file_exists($target_dir)) {
        mkdir($target_dir, 0777, true);
    }
    $rdispense = R::dispense('memberships');
    $rdispense->member_name= $name;
    $rdispense->phone = $phone;
    $rdispense->address = $address;
    $rdispense->egy_card_num= $etihadnum; 
    $rdispense->id_num = $national;
    $rdispense->commercial_register_num = $commerce; 
    $rdispense->tax_card_num = $taax;
    $rdispense->egy_card_expire_date = $ettihad;
    $rdispense->request_status = $_POST['status'];
    $rdispense->legal_position = $legal_position;
        $images = [];
    foreach ($_FILES['image']['name'] as $key => $val) {
        if ($_FILES['image']['tmp_name'][$key] != "") {
            $imgname = time() . "_" . $_FILES['image']['name'][$key];
            move_uploaded_file($_FILES['image']['tmp_name'][$key], "../upload/memberShips/" . $imgname);
            $images[] = $imgname;
        }
    }
    $rdispense->application_image = implode(',', $images);
    $etihad = [];
    if (isset($_FILES['etihadimg'])) {
        foreach ($_FILES['etihadimg']['name'] as $key => $val) {
            if ($_FILES['etihadimg']['tmp_name'][$key] != "") {
                $etihadName = time() . "_" . rand(100, 999) . "_" . $_FILES['etihadimg']['name'][$key];
                move_uploaded_file($_FILES['etihadimg']['tmp_name'][$key], "../upload/memberShips/" . $etihadName);
                $etihad[] = $etihadName;
            }
        }
    }
    $rdispense->egy_card = implode(',', $etihad);
    $ids = [];
    if (isset($_FILES['idimg'])) {
        foreach ($_FILES['idimg']['name'] as $key => $val) {
            if ($_FILES['idimg']['tmp_name'][$key] != "") {
                $idName = time() . "_" . rand(100, 999) . "_" . $_FILES['idimg']['name'][$key];
                move_uploaded_file($_FILES['idimg']['tmp_name'][$key], "../upload/memberShips/" . $idName);
                $ids[] = $idName;
            }
        }
    }
    $rdispense->id_img = implode(',', $ids);
    $commercesimg = [];
    if (isset($_FILES['commerceimg'])) {
        foreach ($_FILES['commerceimg']['name'] as $key => $val) {
            if ($_FILES['commerceimg']['tmp_name'][$key] != "") {
                $commerceName = time() . "_" . rand(100, 999) . "_" . $_FILES['commerceimg']['name'][$key];
                move_uploaded_file($_FILES['commerceimg']['tmp_name'][$key], "../upload/memberShips/" . $commerceName);
                $commercesimg[] = $commerceName;
            }
        }
    }
    $rdispense->commercial_register = implode(',', $commercesimg);
    $taxes = [];
    if (isset($_FILES['taximg'])) {
        foreach ($_FILES['taximg']['name'] as $key => $val) {
            if ($_FILES['taximg']['tmp_name'][$key] != "") {
                $taxName = time() . "_" . rand(100, 999) . "_" . $_FILES['taximg']['name'][$key];
                move_uploaded_file($_FILES['taximg']['tmp_name'][$key], "../upload/memberShips/" . $taxName);
                $taxes[] = $taxName;
            }
        }
    }
    $rdispense->tax_card = implode(',', $taxes);
    $dec = [];
    if (isset($_FILES['decimg'])) {
        foreach ($_FILES['decimg']['name'] as $key => $val) {
            if ($_FILES['decimg']['tmp_name'][$key] != "") {
                $decName = time() . "_" . rand(100, 999) . "_" . $_FILES['decimg']['name'][$key];
                move_uploaded_file($_FILES['decimg']['tmp_name'][$key], "../upload/memberShips/" . $decName);
                $dec[] = $decName;
            }
        }
    }
    $rdispense->board_decision =  implode(',', $dec);
    $rdispense->personal_photo = $your_img;
    $rdispense->sys_date = date("Y-m-d H:i:s");
    $rdispense->userid = $_SESSION['userid'];
    $rdispense->isdel = 0;
    
    $id = R::store($rdispense);
    return $id;
}

function update() {

    $id = $_POST['id'];
    $name = $_POST['name'];
    $phone = $_POST['phone'];
    $address = $_POST['address'];
    $etihadnum = $_POST['etihadnum'];
    $national = $_POST['national'];
    $commerce= $_POST['commerce'];
    $taax = $_POST['tax']; 
    $ettihad= $_POST['ettihad']; 
    $legal_position = $_POST['legal_position'];
    $id_img = uploadupdate('idimg', 'oldidimg', False, 0, 0, 'memberShips');
    $session = $_POST['session'];
    $rupdate = R::load('memberships', $id);
    $rupdate->member_name= $name;
    $rupdate->phone = $phone;
    $rupdate->address = $address;
    $rupdate->egy_card_num= $etihadnum; 
    $rupdate->id_num = $national;
    $rupdate->commercial_register_num = $commerce; 
    $rupdate->tax_card_num = $taax;
    $rupdate->legal_position = $legal_position;
    $rupdate->egy_card_expire_date = $ettihad;
    $rupdate->request_status = $_POST['status'];
    function up($input, $old) {
        if (!empty($_FILES[$input]['name'][0])) {
            $files = [];
            foreach ($_FILES[$input]['name'] as $k => $v) {
                $n = time() . "_" . rand(111, 999) . "_" . $v;
                move_uploaded_file($_FILES[$input]['tmp_name'][$k], "../upload/memberShips/" . $n);
                $files[] = $n;
            }
            return implode(',', $files);
        }
        return $_POST[$old];
    }
    $rupdate->application_image   = up('image', 'imageurl');
    $rupdate->egy_card            = up('etihadimg', 'oldetihadimg');
    $rupdate->id_img              = up('idimg', 'oldidimg');
    $rupdate->commercial_register = up('commerceimg', 'old_commerceimg');
    $rupdate->tax_card            = up('taximg', 'old_taximg');
    $rupdate->board_decision      = up('decimg', 'old_decimg');
    $rupdate->personal_photo = uploadupdate('yourimg', 'old_personal_photo', False, 0, 0, 'memberShips');
    $rupdate->sys_date =  date("Y-m-d H:i:s");
    $rupdate->userid = $_SESSION['userid'];
    $rupdate->isdel = 0;
    
   
    $id = R::store($rupdate);
}

function deleteFinaly($id) { 
    
    $rupdates = R::load('memberships', $id);
    
    if ($rupdates->id > 0) {
        $rupdates->isdel = 1;
        R::store($rupdates);
    }
}