<?php
include("checklogin.php");
include("../includes/inc.php");
$metatitle = "Add | Edit Blog";
if($_REQUEST['q']=='Check_Sub_Category_Slug_URL') {  
  $filename = create_valid_flnm($_REQUEST['slugName']);
  $prod_qry = db_query("SELECT * FROM our_blogs WHERE filename='".$filename."' ");
  if(db_num_rows($prod_qry)==0) {
    echo "1|".$filename;
  }
  else {
    echo "2|";
  }
  exit;
}
include("header.php");
?>
<script src="https://cdn.ckeditor.com/4.25.1-lts/standard/ckeditor.js"></script>
<section class="content-header mt-2">
  <div class="container-fluid">
    <div class="row mb-2">
      <div class="col-sm-6">
        <h6>Add | Edit Blog</h6>
      </div>
      <div class="col-sm-6 text-right">
        <ol class="breadcrumb float-sm-right">
          <li class="breadcrumb-item"><a href="<?php echo ADMIN_SITE_URL; ?>"> <i class="fa fa-dashboard"></i>
              Dashboard</a></li>
          <li class="breadcrumb-item"><a href="<?php echo ADMIN_SITE_URL ?>/manage_blog.php">Manage Blog</a></li>
          <li class="breadcrumb-item active">Add | Edit Blog</li>
        </ol>
      </div>
    </div>
  </div>
</section>

<section class="content-header mt-4">
  <div class="container-fluid">
    <?php
    $errorMsg = '';
    $successmsg = '';
    $reqArr = array();

    if (isset($_POST['pID']) && $_POST['pID'] == 'addeditForm') {

      $extension_allow = array('png', 'jpeg', 'jpg');

      if (!empty($_FILES['blogImg']['name'])) {
        $ext = strtolower(pathinfo($_FILES['blogImg']['name'], PATHINFO_EXTENSION));
        if (!in_array($ext, $extension_allow)) {
          $errorMsg .= 'Only Upload JPEG, JPG, PNG Format in Blog Image<br>';
        }
      }

      if (!empty($_FILES['blogBigImg']['name'])) {
        $ext = strtolower(pathinfo($_FILES['blogBigImg']['name'], PATHINFO_EXTENSION));
        if (!in_array($ext, $extension_allow)) {
          $errorMsg .= 'Only Upload JPEG, JPG, PNG Format in Inner Image<br>';
        }
      }

      if (empty($errorMsg)) {

        if (!empty($_POST['slno'])) {

          $check_qry = db_query("SELECT * FROM our_blogs WHERE filename = '" . trim($_POST['filename']) . "' AND slno != '" . $_POST['slno'] . "' ");

          if (db_num_rows($check_qry) == 0) {
            db_query("UPDATE our_blogs SET 
              blog_title = '" . db_real_escape(trim($_POST['blog_title'])) . "', 
              posted_by = '" . db_real_escape(trim($_POST['posted_by'])) . "', 
              posted_date = '" . $_POST['posted_date'] . "', 
              blog_short_desc = '" . db_real_escape(trim($_POST['blog_short_desc'])) . "', 
              blog_desc = '" . db_real_escape(trim($_POST['blog_desc'])) . "', 
              display_status = '" . $_POST['display_status'] . "', 
              filename = '" . trim($_POST['filename']) . "', 
              meta_title = '" . addslashes($_POST['meta_title']) . "', 
              meta_keyword = '" . addslashes($_POST['meta_keyword']) . "', 
              meta_desc = '" . addslashes($_POST['meta_desc']) . "', 
              parent_id = '" . $_POST['parent_id'] . "' 
              WHERE slno = '" . $_POST['slno'] . "' ");

            $successmsg = 'Y';
          } else {
            $errorMsg = "Blog Title Already Exist";
          }

        } else {

          $check_qry = db_query("SELECT * FROM our_blogs WHERE filename = '" . trim($_POST['filename']) . "' ");

          if (db_num_rows($check_qry) == 0) {
            db_query("INSERT IGNORE INTO our_blogs SET 
              blog_title = '" . db_real_escape(trim($_POST['blog_title'])) . "', 
              posted_by = '" . db_real_escape(trim($_POST['posted_by'])) . "', 
              posted_date = '" . $_POST['posted_date'] . "', 
              blog_short_desc = '" . db_real_escape(trim($_POST['blog_short_desc'])) . "', 
              blog_desc = '" . db_real_escape(trim($_POST['blog_desc'])) . "', 
              display_status = '" . $_POST['display_status'] . "', 
              filename = '" . trim($_POST['filename']) . "', 
              meta_title = '" . addslashes($_POST['meta_title']) . "', 
              meta_keyword = '" . addslashes($_POST['meta_keyword']) . "', 
              meta_desc = '" . addslashes($_POST['meta_desc']) . "', 
              recv_date = '" . date("Y-m-d H:i:s") . "', 
              parent_id = '" . $_POST['parent_id'] . "' ");

            $_POST['slno'] = db_insert_id($GLOBALS['con']);
            $successmsg = 'Y';
          } else {
            $errorMsg = "Blog Title Already Exist";
          }
        }

        if ($successmsg == 'Y' && empty($errorMsg)) {

          $upload_base_dir = dirname(dirname(__FILE__)) . "/frontend/blogimg/";

          if (!file_exists($upload_base_dir)) {
            mkdir($upload_base_dir, 0755, true);
          }

          if (!empty($_FILES['blogImg']['name']) && !empty($_POST['slno']) && $_FILES['blogImg']['error'] == 0) {
            $ext = strtolower(pathinfo($_FILES['blogImg']['name'], PATHINFO_EXTENSION));
            $image_name = $_POST['slno'] . "." . $ext;
            $image_upload_path = $upload_base_dir . $image_name;
            if (move_uploaded_file($_FILES['blogImg']['tmp_name'], $image_upload_path)) {
              chmod($image_upload_path, 0644);
              db_query("UPDATE our_blogs SET blog_img = '" . $image_name . "' WHERE slno = '" . $_POST['slno'] . "' ");
            }
          }

          if (!empty($_FILES['blogBigImg']['name']) && !empty($_POST['slno']) && $_FILES['blogBigImg']['error'] == 0) {
            $ext = strtolower(pathinfo($_FILES['blogBigImg']['name'], PATHINFO_EXTENSION));
            $image_name = $_POST['slno'] . "_big." . $ext;
            $image_upload_path = $upload_base_dir . $image_name;
            if (move_uploaded_file($_FILES['blogBigImg']['tmp_name'], $image_upload_path)) {
              chmod($image_upload_path, 0644);
              db_query("UPDATE our_blogs SET blog_big_img = '" . $image_name . "' WHERE slno = '" . $_POST['slno'] . "' ");
            }
          }

          // ✅ FIXED: Proper redirect to manage_blog.php after successful save
          header("Location: " . ADMIN_SITE_URL . "/manage_blog.php?success=yes");
          exit;
        }
      }
    }

    // Fetch existing record for editing
    if (!empty($_REQUEST['slno'])) {
      $req_qry = db_query("SELECT * FROM our_blogs WHERE slno = '" . $_REQUEST['slno'] . "'");
      if (db_num_rows($req_qry) > 0) {
        $reqArr = db_fetch_assoc($req_qry);
        $_POST['blog_title']      = $reqArr['blog_title'];
        $_POST['posted_by']       = $reqArr['posted_by'];
        $_POST['posted_date']     = $reqArr['posted_date'];
        $_POST['blog_short_desc'] = $reqArr['blog_short_desc'];
        $_POST['blog_desc']       = $reqArr['blog_desc'];
        $_POST['filename']        = $reqArr['filename'];
        $_POST['meta_title']      = $reqArr['meta_title'];
        $_POST['meta_desc']       = $reqArr['meta_desc'];
        $_POST['meta_keyword']    = $reqArr['meta_keyword'];
        $_POST['display_status']  = $reqArr['display_status'];
        $_POST['parent_id']       = $reqArr['parent_id'];
      }
    }
    ?>

    <?php if (!empty($errorMsg)) { ?>
      <div class="alert alert-danger">
        <?php echo $errorMsg; ?>
      </div>
    <?php } ?>

    <form name="searchfrm" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" data-parsley-validate autocomplete="off" enctype="multipart/form-data">
      <div class="row">
        <div class="col-md-12 col-sm-12 col-xs-12">
          <div class="x_panel">
            <div class="x_content">

              <div class="form-group row">
                <label class="col-sm-3 form-control-label">* Blog Title</label>
                <div class="col-sm-6">
                  <input class="form-control" id="blog_title" required name="blog_title" type="text"
                    value="<?php echo isset($_POST['blog_title']) ? htmlspecialchars($_POST['blog_title']) : ''; ?>">
                </div>
              </div>

              <div class="row mb-3">
                <label class="col-sm-3 form-control-label">&nbsp;Slug Name</label>
                <div class="col-sm-5">
                  <input class="form-control slug_name" value="<?php echo isset($_POST['filename']) ? htmlspecialchars($_POST['filename']) : ''; ?>" type="text" required>
                </div>
              </div>

              <div class="row mb-3">
                <label class="col-sm-3 form-control-label">&nbsp;Slug URL</label>
                <div class="col-sm-5">
                  <input class="form-control filename" name="filename" type="text" value="<?php echo isset($_POST['filename']) ? htmlspecialchars($_POST['filename']) : ''; ?>" required readonly>
                </div>
                <span class="slug_url_status"></span>
              </div>

              <div class="form-group row">
                <label class="col-sm-3 form-control-label">* Posted by / Author</label>
                <div class="col-sm-6">
                  <input class="form-control" id="posted_by" required name="posted_by" type="text"
                    value="<?php echo isset($_POST['posted_by']) ? htmlspecialchars($_POST['posted_by']) : ''; ?>">
                </div>
              </div>

              <div class="form-group row">
                <label class="col-sm-3 form-control-label">* Posted Date</label>
                <div class="col-sm-3">
                  <input class="form-control" id="posted_date" required name="posted_date" type="date"
                    value="<?php echo isset($_POST['posted_date']) ? $_POST['posted_date'] : ''; ?>">
                </div>
              </div>

              <div class="row mb-3">
                <label class="col-sm-3 form-control-label">Upload Blog Theme</label>
                <div class="col-sm-8">
                  <input name="blogImg" type="file">
                  <?php if (!empty($reqArr['blog_img'])) { ?>
                    &nbsp;&nbsp;<a href="<?php echo SITE_URL; ?>/frontend/blogimg/<?php echo $reqArr['blog_img']; ?>" target="_blank"><small style="font-size:14px;">View Image</small></a>
                  <?php } ?>
                  &nbsp;&nbsp;
                  <small class="text-danger" style="font-size:12px;">Spec: (W:500px &amp; H:333px) and JPEG,JPG,PNG only (max 35KB)</small>
                </div>
              </div>

              <div class="row mb-3">
                <label class="col-sm-3 form-control-label">Upload Inner Image</label>
                <div class="col-sm-8">
                  <input name="blogBigImg" type="file">
                  <?php if (!empty($reqArr['blog_big_img'])) { ?>
                    &nbsp;&nbsp;<a href="<?php echo SITE_URL; ?>/frontend/blogimg/<?php echo $reqArr['blog_big_img']; ?>" target="_blank"><small style="font-size:14px;">View Image</small></a>
                  <?php } ?>
                  &nbsp;&nbsp;
                  <small class="text-danger" style="font-size:12px;">Spec: (W:824px &amp; H:224px) and JPEG,JPG,PNG only (max 110KB)</small>
                </div>
              </div>

              <div class="form-group row">
                <label class="col-sm-3 form-control-label">Blog Short Description</label>
                <div class="col-sm-8">
                  <textarea class="form-control" name="blog_short_desc" style="height:100px;"><?php echo isset($_POST['blog_short_desc']) ? htmlspecialchars($_POST['blog_short_desc']) : ''; ?></textarea>
                </div>
              </div>

              <div class="form-group row">
                <label class="col-sm-3 form-control-label">* Blog Description</label>
                <div class="col-sm-8">
                  <textarea class="form-control blog_desc ck-editor" id="blog_desc" name="blog_desc"><?php echo isset($_POST['blog_desc']) ? $_POST['blog_desc'] : ''; ?></textarea>
                </div>
              </div>

              <div class="row mb-3">
                <label class="col-sm-3 form-control-label">* Meta Title</label>
                <div class="col-sm-8">
                  <input placeholder="Meta Title" class="form-control" required name="meta_title" type="text"
                    value="<?php echo isset($_POST['meta_title']) ? htmlspecialchars($_POST['meta_title']) : ''; ?>">
                </div>
              </div>

              <div class="mb-2 row">
                <label class="col-md-3 form-control-label">&nbsp;Meta Keywords</label>
                <div class="col-md-8">
                  <textarea class="form-control" name="meta_keyword" rows="2"><?php echo isset($_POST['meta_keyword']) ? htmlspecialchars($_POST['meta_keyword']) : ''; ?></textarea>
                </div>
              </div>

              <div class="mb-2 row">
                <label class="col-md-3 form-control-label">&nbsp;Meta Desc</label>
                <div class="col-md-8">
                  <textarea class="form-control" name="meta_desc" rows="2"><?php echo isset($_POST['meta_desc']) ? htmlspecialchars($_POST['meta_desc']) : ''; ?></textarea>
                </div>
              </div>

              <div class="form-group row">
                <label class="col-sm-3 form-control-label">* Display Status</label>
                <div class="col-sm-3">
                  <select name="display_status" class="form-control" id="display_status" required>
                    <option value="">-- Select One --</option>
                    <?php
                    $status_arr = array('Y' => 'Active', 'N' => 'Inactive');
                    foreach ($status_arr as $key => $value) {
                      $selected = (isset($_POST['display_status']) && $_POST['display_status'] == $key) ? 'selected' : '';
                    ?>
                      <option value="<?php echo $key; ?>" <?php echo $selected; ?>><?php echo $value; ?></option>
                    <?php } ?>
                  </select>
                </div>
              </div>

              <div class="form-group row">
                <label class="col-sm-3 form-control-label">&nbsp;</label>
                <div class="col-sm-3">
                  <input type="hidden" name="pID" value="addeditForm">
                  <input type="hidden" name="slno" value="<?php echo isset($_REQUEST['slno']) ? $_REQUEST['slno'] : ''; ?>">
                  <input type="hidden" name="parent_id" value="<?php echo isset($_POST['parent_id']) ? $_POST['parent_id'] : '0'; ?>">
                  <button type="submit" class="btn btn-info bg-info text-white"><i class="fa fa-save"></i> SUBMIT</button>
                </div>
              </div>

            </div>
          </div>
        </div>
      </div>
    </form>
  </div>
</section>

<?php include("footer.php"); ?>

<script type="text/javascript">
$(document).on("input", ".slug_name", function(e) {
  var slugName = $(this).val();
  if (slugName != '') {
    jQuery.ajax({
      type: 'POST',
      url: '<?php echo ADMIN_SITE_URL; ?>/addedit_blog.php',
      data: 'slugName=' + slugName + '&q=Check_Sub_Category_Slug_URL',
      dataType: 'html',
      success: function(responseData, status, XMLHttpRequest) {
        var gData = responseData.split("|");
        if (gData[0] == 1) {
          $('.slug_url_status').html("");
          $('.filename').val(gData[1]);
        } else {
          $('.filename').val('');
          $('.slug_url_status').html("<span style='color:#e11f26'>Slug URL already Exist</span>");
        }
      }
    });
  }
});

$(document).ready(function() {
  CKEDITOR.replace('blog_desc', {
    extraAllowedContent: 'p(*)' + ';' + 'ul(*)' + ';' + 'h1(*)' + ';' + 'h2(*)' + ';' + 'h3(*)' + ';' + 'h4(*)' + ';' + 'h5(*)' + ';' + 'div(*)' + ';' + 'li(*)'
  });
});
</script>

</body>
</html>