<?php require_once 'classloader.php'; ?>
<?php 
if (!$userObj->isLoggedIn()) {
  header("Location: login.php");
}

if ($userObj->isAdmin()) {
  header("Location: ../../1_api/admin/index.php");
} 
?>
<!doctype html>
  <html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://fonts.googleapis.com/css2?family=Instrument+Sans:wght@400;600&display=swap" rel="stylesheet">

    <style>
      :root {
        --primary: #6CA6CD; 
        --accent: #F2C94C;  
        --light: #FDFDF6; 
      }
      body {
        font-family: 'Instrument Sans', sans-serif;
      }
      .bg-primary { background-color: var(--primary); }
      .bg-accent { background-color: var(--accent); }
      .bg-light { background-color: var(--light); }
      .text-primary { color: var(--primary); }
    </style>
  </head>
  <body class="bg-light min-h-screen flex flex-col">
    <?php include 'includes/navbar.php'; ?>

    <!-- main content -->
    <main class="container mx-auto px-6 py-12 flex-grow">
      <h2 class="text-2xl font-semibold text-primary text-center mb-10">Hello there and welcome! <span class="text-green-500"><?php echo $_SESSION['username']; ?></span>. Add Proposal Here!</h2>

      <div class="grid md:grid-cols-3 gap-8 max-w-7xl mx-auto">
        
        <!-- Add Proposal Form -->
        <div class="md:col-span-1">
          <div class="bg-white border border-gray-200 rounded-2xl shadow-md">
            <div class="bg-accent text-white px-5 py-3 rounded-t-2xl">
              <h3 class="text-lg font-semibold">Add New Proposal</h3>
            </div>
            <div class="p-6">
              <form action="core/handleForms.php" method="POST" enctype="multipart/form-data" class="space-y-4">
                <?php  
                  if (isset($_SESSION['message']) && isset($_SESSION['status'])) {
                    if ($_SESSION['status'] == "200") {
                      echo "<div class='bg-green-100 text-green-800 border border-green-300 px-4 py-3 rounded-lg mb-4'>{$_SESSION['message']}</div>";
                    } else {
                      echo "<div class='bg-red-100 text-red-800 border border-red-300 px-4 py-3 rounded-lg mb-4'>{$_SESSION['message']}</div>"; 
                    }
                    unset($_SESSION['message']);
                    unset($_SESSION['status']);
                  }
                ?>
                <div>
                  <label for="description" class="block text-sm font-medium text-gray-700">Description</label>
                  <textarea name="description" id="description" rows="3" class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-primary focus:border-primary" required></textarea>
                </div>
                <div class="grid grid-cols-2 gap-4">
                  <div>
                    <label for="min_price" class="block text-sm font-medium text-gray-700">Minimum Price</label>
                    <input type="number" name="min_price" id="min_price" class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-primary focus:border-primary" required>
                  </div>
                  <div>
                    <label for="max_price" class="block text-sm font-medium text-gray-700">Maximum Price</label>
                    <input type="number" name="max_price" id="max_price" class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-primary focus:border-primary" required>
                  </div>
                </div>
                <div>
                  <label for="category_id" class="block text-sm font-medium text-gray-700">Category</label>
                  <select name="category_id" id="category_id" class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-primary focus:border-primary" required>
                      <option value="">Select Category</option>
                      <?php
                      require_once __DIR__ . '../../../1_api/admin/classes/Category.php';
                      $categoryObj = new Category();
                      $categories = $categoryObj->getCategories();
                      foreach ($categories as $cat) {
                          echo "<option value='{$cat['category_id']}'>{$cat['category_name']}</option>";
                      }
                      ?>
                  </select>
                </div>
                <div>
                  <label for="subcategory_id" class="block text-sm font-medium text-gray-700">Subcategory</label>
                  <select name="subcategory_id" id="subcategory_id" class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-primary focus:border-primary" required>
                      <option value="">Select Category First</option>
                  </select>
                </div>
                <div>
                  <label for="image" class="block text-sm font-medium text-gray-700">Image</label>
                  <input type="file" name="image" id="image" class="mt-1 block w-full text-sm text-gray-500 file:mr-4 file:py-2 file:px-4 file:rounded-full file:border-0 file:text-sm file:font-semibold file:bg-primary file:text-white hover:file:bg-primary-dark" required>
                </div>
                <div>
                  <button type="submit" name="insertNewProposalBtn" class="w-full flex justify-center py-2 px-4 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-primary hover:bg-primary-dark focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-primary">
                    Add Proposal
                  </button>
                </div>
              </form>
            </div>
          </div>
        </div>

        <!-- Proposals List -->
        <div class="md:col-span-2 space-y-6">
          <?php $getProposals = $proposalObj->getProposals(); ?>
          <?php foreach ($getProposals as $proposal) { ?>
          <div class="bg-white border border-gray-200 rounded-2xl shadow-md">
            <div class="p-6">
              <div class="flex items-start gap-6">
                <img src="<?php echo '../images/' . $proposal['image']; ?>" alt="" class="w-48 h-32 object-cover rounded-lg">
                <div class="flex-grow">
                  <h3 class="text-xl font-semibold text-primary"><a href="other_profile_view.php?user_id=<?php echo $proposal['user_id']; ?>"><?php echo $proposal['username']; ?></a></h3>
                  <p class="text-sm text-gray-500 mb-2"><i><?php echo date("F j, Y, g:i a", strtotime($proposal['proposals_date_added'])); ?></i></p>
                  <p class="text-gray-700 mb-3"><?php echo $proposal['description']; ?></p>
                  <h4 class="text-lg font-semibold text-primary"><i><?php echo number_format($proposal['min_price']) . " - " . number_format($proposal['max_price']); ?> PHP</i></h4>
                </div>
              </div>
            </div>
          </div>
          <?php } ?>
        </div>

      </div>
    </main>

    <script src="https://code.jquery.com/jquery-3.7.0.js"></script>
    <script>
    $(document).ready(function(){
        $('#category_id').on('change', function(){
            var categoryID = $(this).val();
            if(categoryID){
                $.ajax({
                    type:'GET',
                    url:'../../1_api/admin/ajax_get_subcategories.php',
                    data:'category_id='+categoryID,
                    dataType: 'json', // Explicitly set the data type
                    success:function(data){
                        $('#subcategory_id').html('<option value="">Select Subcategory</option>'); 
                        $.each(data, function(index, value) {
                            $('#subcategory_id').append('<option value="'+ value.subcategory_id +'">'+ value.subcategory_name +'</option>');
                        });
                    },
                    error: function(xhr, status, error) {
                        // Log the error for debugging
                        console.error("AJAX Error: " + status + " - " + error);
                        console.log(xhr.responseText);
                        $('#subcategory_id').html('<option value="">Error loading subcategories</option>');
                    }
                }); 
            }else{
                $('#subcategory_id').html('<option value="">Select Category First</option>');
            }
        });
    });
    </script>

  </body>
</html>