<?php 

session_start();  // MUST BE FIRST - before any HTML output

$page_title = "Register | TrustMed"; 
include('includes/db.php');

/* ==========================
   LOGOUT HANDLER
========================== */
if (isset($_GET['logout'])) {
    session_unset();
    session_destroy();
    header("Location: login.php");
    exit;
}

/* ==========================
   LIVE AJAX VALIDATION
========================== */
if(isset($_POST['ajax'])){
    $type = $_POST['type'] ?? '';
    $value = trim($_POST['value'] ?? '');

    header("Content-Type: text/plain");

    if ($type && $value) {

        if ($type === 'TIN') {
            $stmt = $pdo->prepare("SELECT id FROM facility WHERE tin_number = ?");
            $stmt->execute([$value]);
            echo $stmt->fetch() ? 'exists' : 'ok';
            exit;
        }

        if ($type === 'email') {
            $stmt = $pdo->prepare("SELECT id FROM users WHERE email = ?");
            $stmt->execute([$value]);
            echo $stmt->fetch() ? 'exists' : 'ok';
            exit;
        }

        if ($type === 'phone') {
            $stmt = $pdo->prepare("SELECT id FROM users WHERE phone = ?");
            $stmt->execute([$value]);
            echo $stmt->fetch() ? 'exists' : 'ok';
            exit;
        }
    }

    echo "invalid";
    exit;
}

/* ==========================
   AJAX FORM SUBMIT (REGISTER)
========================== */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['ajax_submit'])) {

    header("Content-Type: application/json");

    // Facility
    $facility_name = trim($_POST['facility_name'] ?? '');
    $category      = trim($_POST['category'] ?? '');
    $tin_number    = trim($_POST['tin_number'] ?? '');
    $province      = trim($_POST['province'] ?? '');
    $district      = trim($_POST['district'] ?? '');
    $sector        = trim($_POST['sector'] ?? '');
    $cell          = trim($_POST['cell'] ?? '');
    $village       = trim($_POST['village'] ?? '');

    // User
    $username         = trim($_POST['username'] ?? '');
    $email            = trim($_POST['email'] ?? '');
    $phone            = trim($_POST['phone'] ?? '');
    $password         = $_POST['password'] ?? '';
    $confirm_password = $_POST['confirm_password'] ?? '';

    // VALIDATION
    $errors = [];

    // Facility validation
    if (!$facility_name) $errors[] = "Facility Name is required";
    if (!$category)      $errors[] = "Facility Category is required";
    if (!$tin_number)    $errors[] = "TIN Number is required";
    if (!$province)      $errors[] = "Province is required";
    if (!$district)      $errors[] = "District is required";
    if (!$sector)        $errors[] = "Sector is required";
    if (!$cell)          $errors[] = "Cell is required";
    if (!$village)       $errors[] = "Village is required";

    // User validation
    if (!$username) $errors[] = "Username is required";
    if (!$email)    $errors[] = "Email is required";

    if ($email && !filter_var($email, FILTER_VALIDATE_EMAIL))
        $errors[] = "Invalid Email format";

    if (!$phone) $errors[] = "Phone is required";
    if (!$password) $errors[] = "Password is required";
    if (!$confirm_password) $errors[] = "Confirm Password is required";

    if ($password && $confirm_password && $password !== $confirm_password)
        $errors[] = "Passwords do not match";

    if ($errors) {
        echo json_encode(["status" => "error", "errors" => $errors]);
        exit;
    }

    /* ==========================
       DATABASE OPERATIONS
    ========================== */
    try {

        $pdo->beginTransaction();

        // Check duplicate TIN
        $stmt = $pdo->prepare("SELECT id FROM facility WHERE tin_number = ?");
        $stmt->execute([$tin_number]);
        if ($stmt->fetch()) {
            throw new Exception("TIN already exists");
        }

        // Insert facility
        $stmt = $pdo->prepare("
            INSERT INTO facility 
            (name, category, tin_number, province, district, sector, cell, village)
            VALUES 
            (:name, :cat, :tin, :prov, :dist, :sec, :cell, :vill)
        ");
        $stmt->execute([
            ':name' => $facility_name,
            ':cat'  => $category,
            ':tin'  => $tin_number,
            ':prov' => $province,
            ':dist' => $district,
            ':sec'  => $sector,
            ':cell' => $cell,
            ':vill' => $village
        ]);

        $facility_id = $pdo->lastInsertId();

        // Check duplicate user
        $stmt = $pdo->prepare("SELECT id FROM users WHERE email = ? OR phone = ?");
        $stmt->execute([$email, $phone]);
        if ($stmt->fetch()) {
            throw new Exception("Email or Phone already exists");
        }

        // Add user (always super_admin for first registration)
        $password_hash = password_hash($password, PASSWORD_DEFAULT);

        $stmt = $pdo->prepare("
            INSERT INTO users (username, email, phone, password_hash, facility_id, status, user_role)
            VALUES (:u, :e, :p, :pass, :f, 'active', 'super_admin')
        ");
        $stmt->execute([
            ':u' => $username,
            ':e' => $email,
            ':p' => $phone,
            ':pass' => $password_hash,
            ':f' => $facility_id
        ]);

        $pdo->commit();

        /* ------------------------------
           SET FLASH MESSAGE IN SESSION
        ------------------------------- */
        $_SESSION['flash_success'] = "Facility & Super Admin Registered Successfully!";
        $_SESSION['user_role'] = "super_admin";
        $_SESSION['facility_id'] = $facility_id;
        $_SESSION['username'] = $username;

        echo json_encode(["status" => "success"]);
        exit;

    } catch (Exception $e) {
        $pdo->rollBack();
        echo json_encode(["status" => "error", "errors" => [$e->getMessage()]]);
        exit;
    }
}


 ?>

<!DOCTYPE html>
<html lang="en" data-textdirection="ltr" class="loading">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimal-ui">
    <meta name="description" content="Robust admin is super flexible, powerful, clean &amp; modern responsive bootstrap 4 admin template with unlimited possibilities.">
    <meta name="keywords" content="admin template, robust admin template, dashboard template, flat admin template, responsive admin template, web app">
    <meta name="author" content="PIXINVENT">
    <title>TrustMed</title>
    <link rel="apple-touch-icon" sizes="60x60" href="app-assets/images/ico/apple-icon-60.png">
    <link rel="apple-touch-icon" sizes="76x76" href="app-assets/images/ico/apple-icon-76.png">
    <link rel="apple-touch-icon" sizes="120x120" href="app-assets/images/ico/apple-icon-120.png">
    <link rel="apple-touch-icon" sizes="152x152" href="app-assets/images/ico/apple-icon-152.png">
    <link rel="shortcut icon" type="image/x-icon" href="app-assets/images/ico/favicon.ico">
    <link rel="shortcut icon" type="image/png" href="app-assets/images/ico/favicon-32.png">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-touch-fullscreen" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="default">
    <!-- BEGIN VENDOR CSS-->
    <link rel="stylesheet" type="text/css" href="app-assets/css/bootstrap.css">
    <!-- font icons-->
    <link rel="stylesheet" type="text/css" href="app-assets/fonts/icomoon.css">
    <link rel="stylesheet" type="text/css" href="app-assets/fonts/flag-icon-css/css/flag-icon.min.css">
    <link rel="stylesheet" type="text/css" href="app-assets/vendors/css/extensions/pace.css">
    <!-- END VENDOR CSS-->
    <!-- BEGIN ROBUST CSS-->
    <link rel="stylesheet" type="text/css" href="app-assets/css/bootstrap-extended.css">
    <link rel="stylesheet" type="text/css" href="app-assets/css/app.css">
    <link rel="stylesheet" type="text/css" href="app-assets/css/colors.css">
    <!-- END ROBUST CSS-->
    <!-- BEGIN Page Level CSS-->
    <link rel="stylesheet" type="text/css" href="app-assets/css/core/menu/menu-types/vertical-menu.css">
    <link rel="stylesheet" type="text/css" href="app-assets/css/core/menu/menu-types/vertical-overlay-menu.css">
    <link rel="stylesheet" type="text/css" href="app-assets/css/pages/login-register.css">
    <!-- END Page Level CSS-->
  </head>
  <br><br><br>
  <body data-open="click" data-menu="vertical-menu" data-col="1-column" class="vertical-layout vertical-menu 1-column  blank-page blank-page">
    <!-- ////////////////////////////////////////////////////////////////////////////-->
    <div class="app-content content container-fluid">
      <div class="content-wrapper">
        <div class="content-header row">
        </div>
        <div class="content-body">
          <section class="flexbox-container">
            <div class="row match-height w-100">
              <!-- Left Column: TrustMed Description -->
              <div class="col-md-6 d-flex flex-column justify-content-center align-items-center">
                <div class="text-center px-3">
                  <h2>TrustMed Medical System</h2>
                  <p class="lead">
                    TrustMed Medical System is dedicated to providing high-quality healthcare solutions. 
                    Our mission is to ensure patient care is efficient, reliable, and accessible.
                  </p>
                  <img src="app-assets/images/logo/logo.jpg" alt="TrustMed Logo" class="img-fluid mt-2">
                </div>
              </div>

              <!-- Right Column: Registration Form -->
              <div class="col-md-6 d-flex justify-content-center">
                <div class="col-md-10 box-shadow-2 p-0">
                  <div class="card border-grey border-lighten-3 px-2 py-2 m-0">
                    <div class="card-header no-border">
                      <div class="card-title text-xs-center">
                        <img src="app-assets/images/logo/robust-logo-dark.png" alt="branding logo">
                      </div>
                      <h6 class="card-subtitle line-on-side text-muted text-xs-center font-small-3 pt-2"><span>Create Account</span></h6>
                    </div>
                    <div class="card-body collapse in">  
                      <div class="card-block">
                        <form class="form" id="regForm">
                          <!-- Step 1: Facility Info -->
                          <div id="step1">
                            <div class="form-body">
                              <div class="row">
                                <div class="col-md-6">
                                  <div class="form-group">
                                    <label for="projectinput1">Facility Name</label>
                                    <input type="text" id="projectinput1" class="form-control" placeholder="Facility Name" name="facility_name">
                                    <span class="text-danger facility-error"></span>
                                  </div>
                                </div>

                                <div class="col-md-6">
                                  <div class="form-group">
                                    <label for="projectinput6">Facility Categories</label>
                                    <select id="projectinput6" name="category" class="form-control">
                                      <option value="0" selected="" disabled="">Select Facility Category</option>
                                      <option value="General Clinic">General Clinic</option>
                                      <option value="Polyclinic">Polyclinic</option>
                                      <option value="Hospital">Hospital</option>
                                    </select>
                                    <span class="text-danger category-error"></span>
                                  </div>
                                </div>
                              </div>

                              <div class="row">
                                <div class="col-md-6">
                                  <div class="form-group">
                                    <label for="projectinput3">TIN Number</label>
                                    <input type="number" id="projectinput3" class="form-control" placeholder="TIN Number" name="tin_number">
                                    <span class="text-danger tin-error"></span>
                                  </div>
                                </div>
                                <div class="col-md-6">
                                  <div class="form-group">
                                    <label for="projectinput4">Contact Number</label>
                                    <input type="text" id="projectinput4" class="form-control" placeholder="Phone" name="phone">
                                    <span class="text-danger phone-error"></span>
                                  </div>
                                </div>
                              </div>

                              <div class="row">
                                <div class="col-md-6">
                                  <div class="form-group">
                                    <label for="projectinput3">Province</label>
                                    <input type="text" id="projectinput3" class="form-control" placeholder="Province" name="province">
                                    <span class="text-danger province-error"></span>
                                  </div>
                                </div>
                                <div class="col-md-6">
                                  <div class="form-group">
                                    <label for="projectinput4">District</label>
                                    <input type="text" id="projectinput4" class="form-control" placeholder="District" name="district">
                                    <span class="text-danger district-error"></span>
                                  </div>
                                </div>
                              </div>

                              <div class="row">
                                <div class="col-md-6">
                                  <div class="form-group">
                                    <label for="projectinput3">Sector</label>
                                    <input type="text" id="projectinput3" class="form-control" placeholder="Sector" name="sector">
                                    <span class="text-danger sector-error"></span>
                                  </div>
                                </div>
                                <div class="col-md-6">
                                  <div class="form-group">
                                    <label for="projectinput4">Cell</label>
                                    <input type="text" id="projectinput4" class="form-control" placeholder="Cell" name="cell">
                                    <span class="text-danger cell-error"></span>
                                  </div>
                                </div>
                                <div class="col-md-6">
                                  <div class="form-group">
                                    <label for="projectinput4">Village</label>
                                    <input type="text" id="projectinput4" class="form-control" placeholder="Village" name="village">
                                    <span class="text-danger village-error"></span>
                                  </div>
                                </div>
                              </div>
                            </div>

                            <div class="form-actions">
                              <button type="button" class="btn btn-primary" id="nextStep">
                                <i class="icon-check2"></i> Next
                              </button>
                            </div>
                          </div>

                          <!-- Step 2: User Info -->
                          <div id="step2" style="display:none;">
                            <div class="form-body">
                              <div class="row">
                                <div class="col-md-6">
                                  <div class="form-group">
                                    <label for="username">Username</label>
                                    <input type="text" class="form-control" placeholder="Username" name="username">
                                    <span class="text-danger username-error"></span>
                                  </div>
                                </div>
                                <div class="col-md-6">
                                  <div class="form-group">
                                    <label for="email">Email</label>
                                    <input type="email" class="form-control" placeholder="Email" name="email">
                                    <span class="text-danger email-error"></span>
                                  </div>
                                </div>
                              </div>

                              <div class="row">
                                <div class="col-md-6">
                                  <div class="form-group">
                                    <label for="phone">Phone</label>
                                    <input type="text" class="form-control" placeholder="Phone" name="phone">
                                    <span class="text-danger phone-error"></span>
                                  </div>
                                </div>
                                <div class="col-md-6">
                                  <div class="form-group">
                                    <label for="password">Password</label>
                                    <input type="password" class="form-control" placeholder="Password" name="password">
                                    <span class="text-danger password-error"></span>
                                  </div>
                                </div>
                              </div>

                              <div class="row">
                                <div class="col-md-6">
                                  <div class="form-group">
                                    <label for="confirm_password">Confirm Password</label>
                                    <input type="password" class="form-control" placeholder="Confirm Password" name="confirm_password">
                                    <span class="text-danger confirm-password-error"></span>
                                  </div>
                                </div>
                              </div>

                              <div class="form-actions">
                                <button type="submit" class="btn btn-primary">
                                  <i class="icon-check2"></i> Register
                                </button>
                              </div>
                            </div>
                          </div>
                        </form>
<!-- BEGIN VENDOR JS-->
    <script src="app-assets/js/core/libraries/jquery.min.js" type="text/javascript"></script>
    <script src="app-assets/vendors/js/ui/tether.min.js" type="text/javascript"></script>
    <script src="app-assets/js/core/libraries/bootstrap.min.js" type="text/javascript"></script>
    <script src="app-assets/vendors/js/ui/perfect-scrollbar.jquery.min.js" type="text/javascript"></script>
    <script src="app-assets/vendors/js/ui/unison.min.js" type="text/javascript"></script>
    <script src="app-assets/vendors/js/ui/blockUI.min.js" type="text/javascript"></script>
    <script src="app-assets/vendors/js/ui/jquery.matchHeight-min.js" type="text/javascript"></script>
    <script src="app-assets/vendors/js/ui/screenfull.min.js" type="text/javascript"></script>
    <script src="app-assets/vendors/js/extensions/pace.min.js" type="text/javascript"></script>
    <!-- BEGIN VENDOR JS-->
    <!-- BEGIN ROBUST JS-->
    <script src="app-assets/js/core/app-menu.js" type="text/javascript"></script>
    <script src="app-assets/js/core/app.js" type="text/javascript"></script>
    <!-- END ROBUST JS-->
<script>
$(document).ready(function(){

    // STEP 1 LIVE VALIDATION
    $('input[name="facility_name"]').on('input', function(){
        if(!$(this).val()) $('.facility-error').text('Facility Name is required');
        else $('.facility-error').text('');
    });

    $('select[name="category"]').on('change', function(){
        if($(this).val()==0) $('.category-error').text('Select Facility Category');
        else $('.category-error').text('');
    });

    $('input[name="tin_number"]').on('input', function(){
        let val = $(this).val();
        if(!val){ $('.tin-error').text('TIN Number is required'); return; }
        $.post('', {ajax:1,type:'TIN',value:val}, function(res){
            if(res==='exists') $('.tin-error').text('TIN already exists');
            else $('.tin-error').text('');
        });
    });

    $('input[name="phone"]').on('input', function(){
        let val = $(this).val();
        if(!val){ $('.phone-error').text('Phone is required'); return; }
        $.post('', {ajax:1,type:'phone',value:val}, function(res){
            if(res==='exists') $('.phone-error').text('Phone already exists');
            else $('.phone-error').text('');
        });
    });

    $('input[name="province"]').on('input', function(){
        if(!$(this).val()) $('.province-error').text('Province is required');
        else $('.province-error').text('');
    });

    $('input[name="district"]').on('input', function(){
        if(!$(this).val()) $('.district-error').text('District is required');
        else $('.district-error').text('');
    });

    $('input[name="sector"]').on('input', function(){
        if(!$(this).val()) $('.sector-error').text('Sector is required');
        else $('.sector-error').text('');
    });

    $('input[name="cell"]').on('input', function(){
        if(!$(this).val()) $('.cell-error').text('Cell is required');
        else $('.cell-error').text('');
    });

    $('input[name="village"]').on('input', function(){
        if(!$(this).val()) $('.cell-error').text('Village is required');
        else $('.village-error').text('');
    });

    // NEXT STEP BUTTON
    $('#nextStep').click(function(){
        let hasError = false;

        $('#step1 input, #step1 select').each(function(){
            if(!$(this).val() || $(this).val()==0) hasError = true;
        });

        if(hasError) alert('Please fill all facility fields correctly');
        else {
            $('#step1').hide();
            $('#step2').show();
        }
    });

    // STEP 2 LIVE VALIDATION
    $('input[name="username"]').on('input', function(){
        if(!$(this).val()) $('.username-error').text('Username is required');
        else $('.username-error').text('');
    });

    $('input[name="email"]').on('input', function(){
        let val = $(this).val();
        if(!val) $('.email-error').text('Email is required');
        else if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(val)) $('.email-error').text('Invalid Email format');
        else {
            $.post('', {ajax:1,type:'email',value:val}, function(res){
                if(res==='exists') $('.email-error').text('Email already exists');
                else $('.email-error').text('');
            });
        }
    });

    $('input[name="phone"]').on('input', function(){
        let val = $(this).val();
        if(!val) $('.phone-error').text('Phone is required');
        else {
            $.post('', {ajax:1,type:'phone',value:val}, function(res){
                if(res==='exists') $('.phone-error').text('Phone already exists');
                else $('.phone-error').text('');
            });
        }
    });

    $('input[name="password"]').on('input', function(){
        if(!$(this).val()) $('.password-error').text('Password is required');
        else $('.password-error').text('');
    });

    $('input[name="confirm_password"]').on('input', function(){
        let val = $(this).val();
        let pwd = $('input[name="password"]').val();
        if(!val) $('.confirm-password-error').text('Confirm Password is required');
        else if(val !== pwd) $('.confirm-password-error').text('Passwords do not match');
        else $('.confirm-password-error').text('');
    });

    // FINAL SUBMIT
    $('#regForm').submit(function(e){
        e.preventDefault();
        $.post('', $(this).serialize()+'&ajax_submit=1', function(data){
            if(data.status==='error'){
                alert(data.errors.join("\n"));
            } else if(data.status==='success'){
                alert('Registration Successful!');
                window.location.href='dashboard.php';
            }
        }, 'json');
    });

});
</script>
