<?php 
include '../connection.php'; 
if(!isset($_SESSION)) session_start();
if(!isset($_SESSION["ID"])){header('Location: index.php');}

$direction = "../assets/img/news/";
$flag = true;
$errors = array();
$errorList = "";
$news_ar = isset($_POST["news_ar"]) ? $_POST["news_ar"] : "";
$news_en = isset($_POST["news_en"]) ? $_POST["news_en"] : "";
$ar_paragraph = isset($_POST["ar_paragraph"]) ? $_POST["ar_paragraph"] : "";
$en_paragraph = isset($_POST["en_paragraph"]) ? $_POST["en_paragraph"] : "";
$ar_summary = isset($_POST["ar_summary"]) ? $_POST["ar_summary"] : "";
$en_summary = isset($_POST["en_summary"]) ? $_POST["en_summary"] : "";
$active = isset($_POST["switch"]) ? $_POST["switch"] : 0;
$news_ar = addslashes($news_ar);
$news_en = addslashes($news_en);
$ar_paragraph = addslashes($ar_paragraph);
$en_paragraph = addslashes($en_paragraph);
$ar_summary = addslashes($ar_summary);
$en_summary = addslashes($en_summary);
if(isset($_POST["save"]))
{
  //check method used
  if ($_SERVER['REQUEST_METHOD'] === 'POST')
  { 
    //nothing
  }
  else
  {
    header( 'Location: show-news.php');
  }
  if(!empty($_FILES["image"]["name"]))
{
    $flagImage = true;
    $image = basename($_FILES["image"]["name"]);
    $image = date("h:i:sa").$image;

    $target_file = $direction.$image;
    $image_Type = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
    if(file_exists($target_file))
    {
      $errors["fileExists"] = "يرجى إختيار الصورة";
      $flag = false;
    }//check file exists
    elseif($image_Type != "jpg" && $image_Type != "png" && $image_Type != "jpeg" && $image_Type != "gif" && $image_Type != "jfif")
    {
      $errors["imageType"] = "يجب أن تكون الصورة بأمتداد (jpg,jpeg,png,gif,jfif)";
      $flag = false;
    }
    elseif($_FILES["image"]["size"] > 5000000)
    {
      $errors["imageSize"] = "يجب أن يكون حجم الصورة أقل من 5 ميجا بايت";
      $flag = false;
    }
}
else
{
    $flagImage = false;
    $image = 'whiteBG.png';
}

  if(empty($news_ar) || empty($news_en) || 
     empty($ar_paragraph) || empty($en_paragraph) ||
     empty($ar_summary) || empty($en_summary))
  {
    $errors["empty"] = "يرجى تعبئة جميع الحقول";
    $flag = false; 
  }  //check if any textbox empty


  if($flag === true)
  {
      if($flagImage == true)
      {
        if(!move_uploaded_file($_FILES["image"]["tmp_name"],$target_file))
        {
          $errors["imageUpload"] = "يرجى إعادة رفع الصورة";
        }
        else
        {
            $date = date('y-m-d');
        $insertSql = "INSERT INTO news (
                newsName_ar,content_ar,summary_ar,
                newsName_en,content_en,summary_en,
                image,status,insertDate,insertUsername)
             VALUES (
                '{$news_ar}','{$ar_paragraph}','{$ar_summary}',
                '{$news_en}','{$en_paragraph}','{$en_summary}',
                '{$image}',$active,'{$date}','{$_SESSION["username"]}')";
          $executeSql = mysqli_query($connection,$insertSql);
          $_SESSION["insertNews"] = 1;
          $news_ar = $news_en = $ar_paragraph = $en_paragraph = $ar_summary = $en_summary = '';
        }//if check store image or not
      }
      elseif($flagImage == false)
      {
          $date = date('y-m-d');
          $insertSql = "INSERT INTO news (
          newsName_ar,content_ar,summary_ar,
          newsName_en,content_en,summary_en,
          image,status,insertDate,insertUsername)
          VALUES (
          '{$news_ar}','{$ar_paragraph}','{$ar_summary}',
          '{$news_en}','{$en_paragraph}','{$en_summary}',
          '{$image}',$active,'{$date}','{$_SESSION["username"]}')";
          $executeSql = mysqli_query($connection,$insertSql);
          $_SESSION["insertNews"] = 1;
          $news_ar = $news_en = $ar_paragraph = $en_paragraph = $ar_summary = $en_summary = '';
      }
  }//if for store image in file
  else
  {
    foreach($errors as $error)
    {
      $errorList .= $error."<br>";
    }
  }
}//end if click save

?>
<!doctype html>
<html lang="ar">
  <head>
    <title>خذ فرصة</title>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- assets / css -->
    <?php include 'cssFile.php'; ?>
  </head>
  <body dir="rtl">

<?php include 'navbar.php';?>
<div class="content-body">
<div class='container' style='margin-top:30px;'>
    <div class='row justify-content-center'>
        <div class='col-md-10'>
        <?php
            if($flag === false)
            {
            echo "
            <div class='alert alert-danger text-right'>
            $errorList
            </div>";
            }
        ?>
    <form  action="<?php echo $_SERVER['PHP_SELF']; ?>" method='post' enctype="multipart/form-data">
            <div class="card text-right" id="add-info">
                <div class="card-header"><h3>إضافة جديد</h3></div>
                <div class="card-body">
                    <div class='form-row'>
                        <div class='form-group col-md'>
                            <label class='ar-info' for="ar-info">المعلومات باللغة العربية</label>                        
                        </div>
                        <!-- End form-group -->
                    </div>
                    <!-- End form row -->
                    <div class='form-row'>
                        <div class='form-group col-md'>
                            <label for="news_ar">إسم الخبر</label>       
                            <input type='text' class='form-control' name='news_ar' value='<?= $news_ar?>'>                 
                        </div>
                        <!-- End form-group -->
                    </div>
                    <!-- End form row -->
                    <div class='form-row'>
                        <div class='form-group col'>
                            <label for="ar-paragraph">محتوى الخبر</label>
                            <textarea class='form-control' rows="3" name="ar_paragraph" style='resize:none;'><?= $ar_paragraph; ?></textarea>                 
                        </div>
                        <!-- end form group -->
                    </div>
                    <!-- end form row -->
                    <div class='form-row'>
                        <div class='form-group col'>
                            <label for="ar-summary">ملخص الخبر</label>
                            <textarea class='form-control' rows="2" name="ar_summary" style='resize:none;'><?= $ar_summary; ?></textarea>                 
                        </div>
                        <!-- end form group -->
                    </div>
                    <!-- end form row -->
                    <div class="form-row">
                    <div class='form-group col-md'>
                            <label class='en-info' for="en-info">المعلومات باللغة الإنجليزية</label>                        
                        </div>
                        <!-- End form-group -->
                    </div>
                    <div class="form-row">
                      <div class='form-group col-md'>
                            <label for="news_en">إسم الخبر</label>       
                            <input type='text' class='form-control' name='news_en' value="<?= $news_en ?>">                                        
                        </div>
                        <!-- End form-group -->
                    </div>
                    <div class="form-row">
                      <div class='form-group col'>
                            <label for="en-paragraph">محتوى الخبر</label>
                            <textarea class='form-control' rows="3" name="en_paragraph" style='resize:none;'><?= $en_paragraph?></textarea>                 
                        </div>
                        <!-- end form group -->
                    </div>
                    <div class="form-row">
                      <div class='form-group col'>
                            <label for="en-summary">ملخص الخبر</label>
                            <textarea class='form-control' rows="2" name="en_summary" style='resize:none;'><?= $en_summary?></textarea>                 
                        </div>
                        <!-- end form group -->
                    </div>
                    <div class='form-row'>
                        <div class='form-group col'>
                        <button class="file-upload-btn" type="button" onclick="$('.file-upload-input').trigger( 'click' )">إضافة صورة جديدة</button>
                        <div class="image-upload-wrap">
                            <input class="file-upload-input" name="image" type='file' onchange="readURL(this);" />
                            <div class="drag-text">
                            <h1><i class="fas fa-image"></i></h1>
                            </div>
                        </div>
                        <div class="file-upload-content">
                            <img class="file-upload-image" src="#" alt="your image" />
                            <div class="image-title-wrap">
                                <button type="button" onclick="removeUpload()" class="remove-image">حذف</button>
                            </div>
                        </div>
                        </div>
                        <!-- End form group -->
                    </div>
                    <!-- End form row -->
                    <div class='form-row'>
                        <div class='form-group col-5'>
                            <div dir='ltr'>
                                <span class="margin-r">تفعيل</span>
                                <label class="el-switch el-switch-green">
                                    <input type="checkbox" id='checkbox' value='1' checked name="switch">
                                    <span class="el-switch-style"></span>
                                </label>
                            </div>
                        </div>
                        <!-- end form group -->
                        <div class="form-group col">
                        <button type="submit" name="save" class="save-image">حفظ</button>
                        </div>
                    </div>
                    <!-- end form row -->
                </div>
                <!-- End card-body -->
            </div>
            <!-- End card -->
    </form>
        </div>
        <!-- End col-md -->
    </div>
    <!-- End row -->
</div>
<!-- End container -->
</div>
<!-- End content-body -->
<!-- assets / js -->
    <?php include 'jsFile.php'; ?>
<script>
<?php
if(!isset($_SESSION))
  session_start();
if(isset($_SESSION["insertNews"]) && $_SESSION["insertNews"] == 1)
{ 
?>
Swal.fire(
  'تم إضافة خبر جديد بنجاح',
  '',
  'success'
)
<?php
$_SESSION["insertNews"] = 0;
}
?>

  </script>
  </body>
</html>
<!-- onload="reloader()" -->
