<?php
require_once('config.php');

if(isset($_POST['add_user'])){
  $acc_pwd = $_POST['UserPassword'];
  $post_form_data = array(
    'UserName' => $_POST['UserName'],
    'UserNameEN' => $_POST['UserNameEN'],
    'UserEmail' => $_POST['UserEmail'],
    'UserDesignation' => $_POST['UserDesignation'],
    'UserPassword' => password_hash($acc_pwd, PASSWORD_BCRYPT),
    'UserLoginKey' => md5(randomString().time()),
    'AccountStatus' => 'active',
    'UserProfile' => 'active',
    'PostAbility' => 'yes',
    'UpdateProfile' => 'active',
    'PostPublish' => 'Manually',
    'CommentAbility' => 'none',
    'FirstVerificationStatus' => 'Verified',
    'JoinDate' => $the_time,
  );

  $insert_now = InsertData('tt_accounts', $post_form_data);

  if ($insert_now) {
      header("Location:".$site_domain."mfit-admin/writer-profile.php?id=$insert_now");
      exit;
  }
}

// Delete writer functionality - GET method (সহজ সমাধান)
if(isset($_GET['delete_id'])){
    $user_id = intval($_GET['delete_id']);
    
    try {
        $delete_query = "DELETE FROM `tt_accounts` WHERE `UserID` = :user_id";
        $stmt = $conn->prepare($delete_query);
        $stmt->bindParam(':user_id', $user_id, PDO::PARAM_INT);
        $stmt->execute();
        
        $_SESSION['success_msg'] = "Writer deleted successfully!";
    } catch (PDOException $e) {
        $_SESSION['error_msg'] = "Error: " . $e->getMessage();
    }
    
    header("Location: ".str_replace('?'.$_SERVER['QUERY_STRING'], '', $_SERVER['REQUEST_URI']));
    exit;
}

// Include Header File
require_once('inc/header.php');

$tt_writers = showAllttdata("tt_accounts", "ORDER BY UserID DESC");

// Display messages
if(isset($_SESSION['success_msg'])){
    echo '<div class="alert alert-success alert-dismissible fade show m-3" role="alert">'.$_SESSION['success_msg'].'<button type="button" class="btn-close" data-bs-dismiss="alert"></button></div>';
    unset($_SESSION['success_msg']);
}
if(isset($_SESSION['error_msg'])){
    echo '<div class="alert alert-danger alert-dismissible fade show m-3" role="alert">'.$_SESSION['error_msg'].'<button type="button" class="btn-close" data-bs-dismiss="alert"></button></div>';
    unset($_SESSION['error_msg']);
}
?>
<main id="main" class="main">
  <div class="row align-items-center">
    <div class="col-6">
      <div class="pagetitle mb-0">
        <h1><?php echo $page_title ?></h1>
      </div>
    </div>
    <div class="col-6">
      <div class="text-end">
        <button type="button" class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#staticBackdrop">Add New Writer</button>
      </div>

      <!-- Modal -->
      <form action="" method="post">
        <div class="modal fade" id="staticBackdrop" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true">
          <div class="modal-dialog">
            <div class="modal-content">
              <div class="modal-header">
                <h1 class="modal-title fs-5" id="staticBackdropLabel">Add User</h1>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
              </div>
              <div class="modal-body">
                <div class="row g-3">
                  <div class="form-group col-md-6">
                    <label class="form-label">Name <span class="text-danger">*</span></label>
                    <input type="text" name="UserName" class="form-control" required>
                  </div>
                  <div class="form-group col-md-6">
                    <label class="form-label">Name English</label>
                    <input type="text" name="UserNameEN" class="form-control">
                  </div>
                  <div class="form-group col-md-12">
                    <label class="form-label">Designation</label>
                    <input type="text" name="UserDesignation" class="form-control">
                  </div>
                  <hr>
                  <div class="form-group mb-2">
                    <label class="form-label">Email <span class="text-danger">*</span></label>
                    <input type="email" name="UserEmail" class="form-control" id="userEmail" required onblur="checkBlockedEmail()">
                  </div>
                  <div class="form-group mb-2">
                    <label class="form-label">Password <span class="text-danger">*</span></label>
                    <input type="text" name="UserPassword" class="form-control" required>
                  </div>
                </div>
              </div>
              <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="submit" name="add_user" class="btn btn-primary">Add Writer</button>
              </div>
            </div>
          </div>
        </div>
      </form>
    </div>
  </div>

  <section class="section mt-4">
    <div class="bg-white rounded-2 py-3">
      <table class="tt_datatable" style="width:100%">
        <thead>
          <tr>
            <th>ID</th>
            <th>Name</th>
            <th class="text-center">Mobile</th>
            <th class="text-center">Email</th>
            <th class="text-center">Location</th>
            <th class="text-center">A/C Status</th>
            <th class="text-center">Post Ability</th>
            <th class="text-center">Action</th>
          </tr>
        </thead>
        <tbody>
        <?php if (!empty($tt_writers)) {
          foreach ($tt_writers as $tt_writer) { ?>
            <tr>
              <td><?php echo $tt_writer['UserID'] ?></td>
              <td><a target="_blank" class="text-dark" href="<?php echo userProfile($tt_writer['UserID']) ?>"><?php echo $tt_writer['UserName'] ?></a></td>
              <td class="text-center"><?php echo $tt_writer['UserMobile'] ?></td>
              <td class="text-center"><?php echo $tt_writer['UserEmail'] ?></td>
              <td class="text-center"><?php echo getSingleValue('mahamudfutureit_loc_districts', 'id', $tt_writer['UserpZilla'], 'name') ?></td>
              <td class="text-center"><?php echo $tt_writer['AccountStatus'] ?></td>
              <td class="text-center"><?php echo $tt_writer['PostAbility'] ?></td>
              <td class="text-center">
                <a class="bg-primary text-white px-2 py-1 rounded text-decoration-none" href="writer-profile.php?id=<?php echo $tt_writer['UserID'] ?>">Profile</a>
                <a class="bg-danger text-white px-2 py-1 rounded text-decoration-none ms-1" href="?delete_id=<?php echo $tt_writer['UserID'] ?>" onclick="return confirm('Are you sure you want to delete writer: <?php echo addslashes($tt_writer['UserName']); ?>?')">Delete</a>
              </td>
            </tr>
          <?php }
        } ?>
        </tbody>
      </table>
    </div>
  </section>
</main>

<script>
// Blocked email check
const blockedEmails = [<?php foreach ($tt_writers as $tt_writer) { echo '"'.$tt_writer['UserEmail'].'",'; } ?>];

function checkBlockedEmail() {
  const emailInput = document.getElementById("userEmail");
  if (blockedEmails.includes(emailInput.value.trim().toLowerCase())) {
    emailInput.value = '';
    alert("This email used another account!");
  }
}
</script>

<?php require_once('inc/footer.php'); ?>