<?php
ob_start();
include('head.php');
include('header.php'); 
include('sidebar.php'); 

// $stmt = $pdo->prepare("SELECT * FROM tblphysicians where isDeleted='N' and id= ? order by id DESC");
$stmt = $pdo->prepare("SELECT tblphysicians.firstName, tblphysicians.lastName,tblphysicians.primarySpecialty,tblphysicians.hospital,
COALESCE(tblphysiciansaddress.email, tblphysicians.email) AS email, 
COALESCE(tblphysiciansaddress.fax, tblphysicians.fax) AS fax,
tblphysicians.license, COALESCE(tblphysiciansaddress.phone, tblphysicians.phone) AS phone,
COALESCE(tblphysiciansaddress.streetAddress, tblphysicians.streetAddress) AS streetAddress,
COALESCE(tblphysiciansaddress.city, tblphysicians.city) AS city, 
COALESCE(tblphysiciansaddress.province, tblphysicians.province) AS province,
COALESCE(tblphysiciansaddress.postalCode, tblphysicians.postalCode) AS postalCode, 
tblphysicians.createdBy, tblphysicians.assignedTo, tblphysicians.physicianType, tblphysicians.createdAt, tblphysicians.id 
FROM tblphysicians LEFT JOIN tblphysiciansaddress ON tblphysicians.id = tblphysiciansaddress.physicianId AND tblphysiciansaddress.addressType = 'Primary' 
WHERE tblphysicians.isDeleted = 'N' AND tblphysicians.id= ?");
$stmt->execute([$_GET['id']]);
$patients = $stmt->fetch();
$ptype = ['Pilot','NP','Transferred Out'];
//check secondary address if present
// $stmt = $pdo->prepare("SELECT COUNT(*) FROM tblphysiciansaddress WHERE tblphysiciansaddress.addressType = 'Secondary' AND tblphysiciansaddress.isDeleted = 'N'
// AND tblphysiciansaddress.physicianId=?");
// $stmt->execute([$_GET['id']]);
// $SecondaryCount = $pdo->query($stmt)->fetchColumn();
$primaryAddress='';
$stmt = $pdo->prepare("SELECT * from tblphysiciansaddress WHERE addressType='Primary' AND isDeleted = 'N' AND physicianId=?");
$stmt->execute([$_GET['id']]);
$primaryAddress = $stmt->fetch();

$secondaryAddress='';
$stmt = $pdo->prepare("SELECT * from tblphysiciansaddress WHERE addressType='Secondary' AND isDeleted = 'N' AND physicianId=?");
$stmt->execute([$_GET['id']]);
$secondaryAddress = $stmt->fetch();


$stmt = $pdo->prepare("SELECT * FROM tblphysicians where isDeleted='N' and id= ? order by id DESC");
$stmt->execute([$_GET['id']]);
$patients = $stmt->fetch();

$stmt8 = $pdo->prepare("SELECT * FROM tblprovince WHERE countryId='1' ORDER BY provinceName ASC");
$stmt8->execute();
$provinces = $stmt8->fetchAll();

$stmt1 = $pdo->prepare("SELECT empId,userName from tbluser WHERE isDeleted='N' AND (
      department = 'R'
      OR (department = 'P' AND userRole REGEXP '(^|,)\\s*RS\\s*(,|$)')
    )");
$stmt1->execute();
$employees = $stmt1->fetchAll();
$error='';
if (isset($_POST['btnSubmit'])) {
    $physicianFirstName = $_POST['firstName'];
    $physicianLastName = $_POST['lastName'];
    $hospital = $_POST['hospital'];
    $license = $_POST['license'];
    $primarySpecialty = $_POST['primarySpecialty'];
    $assignedTo = $_POST['assignedTo'];
    $physicianAddress = $_POST['address'];
    $physicianCity = $_POST['city'];
    $physicianProvince = $_POST['physicianProvince'];
    $physicianPostalCode = $_POST['postalCode'];

    $phone = $_POST['phone'];
    $email = $_POST['email'];
    $fax = $_POST['fax'];
    $notes = $_POST['notes'];
    $createdBy = $_SESSION['empId'];

    // secondary address fields
    $secondary_email = $_POST['secondary-email']?? null;
    $secondary_fax = $_POST['secondary-fax']?? null;
    $secondary_phone = $_POST['secondary-phone']?? null;
    $secondary_physicianAddress = $_POST['secondary-address']?? null;
    $secondary_physicianCity = $_POST['secondary-city']?? null;
    $secondary_physicianProvince = $_POST['secondary-physicianProvince']?? null;
    $secondary_physicianPostalCode = $_POST['secondary-postalCode']?? null;
    $secondary_hospital = $_POST['secondary-hospital']?? null;
    $secondary_notes = $_POST['secondary-notes']?? null;

    $physicianType = $_POST['physicianType']?? null;

        $sql = "UPDATE tblphysicians set  firstName=?, lastName=?, hospital=?,license=?, primarySpecialty=?, streetAddress=?, city=?, province=?, postalCode=?, phone=?, email=?,fax=?,createdBy=?,assignedTo=?,notes=?,physicianType=? where id=?";
        $stmt = $pdo->prepare($sql);
        if ($stmt->execute([$physicianFirstName,$physicianLastName,$hospital,$license,$primarySpecialty,$physicianAddress,$physicianCity,$physicianProvince,$physicianPostalCode, $phone, $email,$fax,$createdBy,$assignedTo,$notes,$physicianType,$_GET['id']])) 
        {      
            //header("location:physicians.php");
            //update primary address details
        if(isset($primaryAddress['id']))
        {
            $stmt = $pdo->prepare("Update tblphysiciansaddress set hospital=?, streetAddress=?, city=?, province=?, postalCode=?, phone=?,
             email=?, fax=?, notes=?, createdBy=? where physicianId=? AND addressType = 'Primary'");
            if ($stmt->execute([$hospital,$physicianAddress,$physicianCity,$physicianProvince,$physicianPostalCode, $phone, $email,$fax,$notes,$createdBy,$_GET['id']])) {
            // header("location:physicians.php"); 
            } else {
            echo "Please try again!";
            }
        }
        else{
            $stmt = $pdo->prepare("INSERT INTO tblphysiciansaddress(physicianId, addressType, hospital, streetAddress, city, province, postalCode, phone, email, fax, notes,isDeleted,createdBy) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)");
            if ($stmt->execute([$_GET['id'], 'Primary', $hospital, $physicianAddress, $physicianCity, $physicianProvince, $physicianPostalCode, $phone, $email, $fax, $notes, 'N',$createdBy]))
            {
            }
            else
            {
                echo "Please try again!";
            }
        }
        //insert secondary address details
        if (isset($secondaryAddress['id'])) {
            $stmt = $pdo->prepare("Update tblphysiciansaddress set hospital=?, streetAddress=?, city=?, province=?, postalCode=?, phone=?,
            email=?, fax=?, notes=?, createdBy=? where physicianId=? AND addressType = 'Secondary'");
            if ($stmt->execute([$secondary_hospital,$secondary_physicianAddress,$secondary_physicianCity,$secondary_physicianProvince,$secondary_physicianPostalCode, $secondary_phone, $secondary_email,$secondary_fax,$secondary_notes,$createdBy,$_GET['id']]))
            {
            // header("location:physicians.php"); 
            } 
            else {
            echo "Please try again!";
            }
            } 
         else {
            $stmt = $pdo->prepare("INSERT INTO tblphysiciansaddress(physicianId, addressType, hospital, streetAddress, city, province, postalCode, phone, email, fax, notes,isDeleted,createdBy) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)");
                if ($stmt->execute([$_GET['id'], 'Secondary', $secondary_hospital, $secondary_physicianAddress, $secondary_physicianCity, $secondary_physicianProvince, $secondary_physicianPostalCode, $secondary_phone, $secondary_email, $secondary_fax, $secondary_notes, 'N',$createdBy]))
                {
                }
                else
                {
                    echo "Please try again!";
                }
        }
        header("location:physicians.php"); 
    }
}
?>
    <style>
        .secondary-address-fields{
           display: none;
        }
        .secondary-address{
            display: inline-block !important;
        }
        .card-header.mgtop.inlineflex {
            padding: 20px;
        }
        a.white{
            color:white;
        }
        .mgtop{
            margin-top:20px;
            margin-bottom:20px;
        }
        /* #example_wrapper select:not([size]) {
            width: 10%;
            margin: 10px;
        } */
        .rxtitle{
            font-size:24px;
            font-weight:600;
        }
        table a.btn {
            /* background: none; */
            height: max-content;
            width: max-content;
            display: inline-flex;
        }
        .dt-length,.dt-search {
            display: flex;
            vertical-align: middle;
            align-items: center;
        }
        .customdewidth{
            margin-left: 15%;
            margin-top: 80px;
            width: 85%;
            background-color: whitesmoke;
        }
        aside{
           width:15%; 
        }
        .deindexpage .dt-search {
            float: right;
        }
        .errormessage{
            color: red;
            padding: 10px 0px;
        }
        body.navigation section .btn-primary{
            background: #9c27b0;
            border-color: #9c27b0;  
            font-weight:600; 
        }
        body.navigation section .btn-primary:hover {
            background-color: #631470;
            border-color: #631470;
        }
        body.navigation section .btn-secondary{
            font-weight:600;
            background: #6c757d;
            border-color: #6c757d;   
        }
        body.navigation section .btn-secondary:hover {
            background-color: #6c757d;
            border-color: #6c757d;
        }
    </style>

    <section class="bgcolordefault deindexpage editPhysician">
        <div class="editWc container-fluid customdewidth">

            <div class="row">
                <div class="col-12 customui">
                    <div class="card">
                        <div class="card-header">
                            <h3 class="card-title">Edit Physician</h3>
                            <div class="offset-10 col-1">
                                <a href="physicians.php" class="btn btn-block btn-secondary bg-gradient-primary">BACK</a>
                            </div>
                        </div>
                        <!-- /.card-header -->
                        <div class="card-body">
                            <!-- /.card-header -->
                            <!-- form start -->
                            <form method="POST">
                                <div class="card-body row">
                                    <div class="form-group col-md-4">
                                        <label for="pspName">Physician Type:</label>
                                            <div class="fixselect">
                                                <select class="form-control select2bs4" id="physicianType" name="physicianType">
                                                    <!-- <option value="">Select Physician Type</option> -->
                                                    <option value="" <?=( $patients['physicianType']=="" ) ? 'selected' : '' ?>>Select Physician Type</option>
                                                    <?php foreach ($ptype as $type) { ?>
                                                    <option value="<?= $type; ?>" <?=( $patients[ 'physicianType']==$type) ? 'selected' : '' ?>><?= $type; ?></option>
                                                    <?php } ?>
                                                </select>
                                            </div>
                                    </div>
                                    <div class='clearfix'></div>
                                    <div class="form-group col-md-4">
                                        <label for="pspName">Physician First Name</label>
                                        <input type="text" readonly class="form-control" name="firstName" value="<?=$patients['firstName'];?>" placeholder="Enter Physician First Name">
                                    </div>
                                    <div class="form-group col-md-4">
                                        <label for="pspName">Physician Last Name</label>
                                        <input type="text" readonly class="form-control" name="lastName" value="<?=$patients['lastName'];?>" placeholder="Enter Physician Last Name">
                                    </div>
                                    <div class="clearfix"></div>
                                    <div class="form-group col-md-4">
                                        <label for="pspName">License</label>
                                        <input type="text" class="form-control" name="license" value="<?=$patients['license'];?>">
                                    </div>
                                    <div class="form-group col-md-4">
                                        <label for="pspName">Physician Primary Specialty:</label>
                                        <input type="text" class="form-control" name="primarySpecialty" value="<?=$patients['primarySpecialty'];?>" placeholder="Enter Primary Specialty">
                                    </div>
                                    <div class='clearfix'></div>
                                    <div class="form-group col-md-4">
                                        <label for="pspName">Assigned To:</label>

                                        <div class="fixselect">
                                            <select class="form-control select2bs4" id="assignedTo" name="assignedTo">
                                                <option value="" <?=( $patients['assignedTo']=="" ) ? 'selected' : '' ?>></option>
                                                <?php foreach ($employees as $emp) { ?>
                                                    <option value="<?= $emp['empId']; ?>" <?=( $patients[ 'assignedTo']==$emp[ 'empId']) ? 'selected' : '' ?>>
                                                        <?= $emp['userName']; ?>
                                                    </option>
                                                    <?php } ?>
                                            </select>
                                        </div>
                                    </div>
                                    <div class='clearfix'></div>
                                    <div class="form-group col-md-4">
                                        <label for="pspName">Email</label>
                                        <input type="email" class="form-control" name="email" value="<?= isset($primaryAddress) && isset($primaryAddress['email']) && !empty($primaryAddress['email']) ? $primaryAddress['email'] : ''; ?>" placeholder="Enter Email">
                                    </div>
                                    <div class="form-group col-md-4">
                                        <label for="pspName">Fax</label>
                                        <input type="text" class="form-control" name="fax" value="<?= isset($primaryAddress) && isset($primaryAddress['fax']) && !empty($primaryAddress['fax']) ? $primaryAddress['fax'] : ''; ?>" placeholder="Enter Fax">
                                    </div>
                                    <div class="clearfix"></div>
                                    <div class="form-group col-md-4">
                                        <label for="pspName">Phone</label>
                                        <input type="text" class="form-control" name="phone" value="<?= isset($primaryAddress) && isset($primaryAddress['phone']) && !empty($primaryAddress['phone']) ? $primaryAddress['phone'] : ''; ?>" placeholder="Enter Phone" data-inputmask="&quot;mask&quot;: &quot;(999) 999-9999&quot;" data-mask="" inputmode="text">
                                    </div>
                                    <div class="clearfix"></div>
                                    <div class="form-group col-md-4">
                                        <label for="pspName">Address</label>
                                        <input type="text" class="form-control" name="address" value="<?= isset($primaryAddress) && isset($primaryAddress['streetAddress']) && !empty($primaryAddress['streetAddress']) ? $primaryAddress['streetAddress'] : ''; ?>" placeholder="Enter Street Address">
                                    </div>

                                    <div class="form-group col-md-4">
                                        <label for="pspName">City</label>
                                        <input type="text" class="form-control" name="city" value="<?= isset($primaryAddress) && isset($primaryAddress['city']) && !empty($primaryAddress['city']) ? $primaryAddress['city'] : ''; ?>" placeholder="Enter City">
                                    </div>
                                    <div class="clearfix"></div>
                                    <div class="form-group col-md-4">
                                        <label for="pspName">Province</label>
                                        <select class="form-control" name='physicianProvince' required id="physicianProvince">
                                            <option>Select Province</option>
                                            <?php foreach ($provinces as $province) { ?>
                                                <option <?php if (isset($primaryAddress[ 'province'])) { if ((isset($primaryAddress)) && ($primaryAddress[ 'province']==$province[ 'provinceName'])) { echo 'selected'; } } ?> value="<?php echo $province['provinceName']; ?>"><?php echo $province['provinceName']; ?></option>
                                                <?php } ?>
                                        </select>
                                    </div>
                                    <div class="form-group col-md-4">
                                        <label for="pspName">Postal Code</label>
                                        <input type="text" class="form-control" name="postalCode" value="<?= isset($primaryAddress) && isset($primaryAddress['postalCode']) && !empty($primaryAddress['postalCode']) ? $primaryAddress['postalCode'] : ''; ?>" placeholder="Enter Postal Code">
                                    </div>
                                    <div class="clearfix"></div>
                                    <div class="form-group col-md-4">
                                        <label for="pspName">Physician Hospital/Site :</label>
                                        <input type="text" class="form-control" name="hospital" value="<?= isset($primaryAddress) && isset($primaryAddress['hospital']) && !empty($primaryAddress['hospital']) ? $primaryAddress['hospital'] : ''; ?>" placeholder="Enter Hospital">
                                    </div>
                                    <div class="form-group col-md-4">
                                        <label for="pspName">Physician Notes :</label>
                                        <textarea class="form-control" name="notes"><?= isset($primaryAddress) && isset($primaryAddress['notes']) && !empty($primaryAddress['notes']) ? $primaryAddress['notes'] : ''; ?></textarea>
                                    </div>

                                    <div class="clearfix"></div>
                                    <div class="form-group col-md-4">
                                        <label for="checkbox" class="secondary-address">Secondary Address&nbsp;</label>
                                        <input type="checkbox" class="form-input secondary-address" id="checkbox" name="checkbox" onclick="toggleAddressFields()">
                                    </div>
                                    <div class="clearfix"></div>
                                    <!-- secondary address fields -->
                                    <div class="card-body row secondary-address-fields" id="secondary-address-fields">
                                        <div class="clearfix"></div>
                                        <div class="form-group col-md-4">
                                            <label for="pspName">Email</label>
                                            <input type="email" class="form-control" name="secondary-email" value="<?= isset($secondaryAddress) && isset($secondaryAddress['email']) && !empty($secondaryAddress['email']) ? $secondaryAddress['email'] : ''; ?>" placeholder="Enter Email">
                                        </div>
                                        <div class="form-group col-md-4">
                                            <label for="pspName">Fax</label>
                                            <input type="text" class="form-control" name="secondary-fax" value="<?= isset($secondaryAddress) && isset($secondaryAddress['fax']) && !empty($secondaryAddress['fax']) ? $secondaryAddress['fax'] : ''; ?>" placeholder="Enter Fax">
                                        </div>
                                        <div class="clearfix"></div>
                                        <div class="form-group col-md-4">
                                            <label for="pspName">Phone</label>
                                            <input type="text" class="form-control" name="secondary-phone" value="<?= isset($secondaryAddress) && isset($secondaryAddress['phone']) && !empty($secondaryAddress['phone']) ? $secondaryAddress['phone'] : ''; ?>" placeholder="Enter Phone" data-inputmask="&quot;mask&quot;: &quot;(999) 999-9999&quot;"
                                            data-mask="" inputmode="text">
                                        </div>
                                        <div class="clearfix"></div>
                                        <div class="form-group col-md-4">
                                            <label for="pspName">Address</label>
                                            <input type="text" class="form-control" name="secondary-address" value="<?= isset($secondaryAddress) && isset($secondaryAddress['streetAddress']) && !empty($secondaryAddress['streetAddress']) ? $secondaryAddress['streetAddress'] : ''; ?>" placeholder="Enter Street Address">
                                        </div>

                                        <div class="form-group col-md-4">
                                            <label for="pspName">City</label>
                                            <input type="text" class="form-control" name="secondary-city" value="<?= isset($secondaryAddress) && isset($secondaryAddress['city']) && !empty($secondaryAddress['city']) ? $secondaryAddress['city'] : ''; ?>" placeholder="Enter City">
                                        </div>
                                        <div class="clearfix"></div>
                                        <div class="form-group col-md-4">
                                            <label for="pspName">Province</label>
                                            <select class="form-control" name='secondary-physicianProvince' required id="secondary-physicianProvince">
                                                <option>Select Province</option>
                                                <?php foreach ($provinces as $province) { ?>
                                                    <option <?php if (isset($secondaryAddress[ 'province'])) { if (isset($secondaryAddress) && $secondaryAddress[ 'province']==$province[ 'provinceName']) { echo 'selected'; } } ?> value="<?php echo $province['provinceName']; ?>"><?php echo $province['provinceName']; ?></option>
                                                    <?php } ?>
                                            </select>
                                        </div>
                                        <div class="form-group col-md-4">
                                            <label for="pspName">Postal Code</label>
                                            <input type="text" class="form-control" id="secondary-postalCode" name="secondary-postalCode" value="<?= isset($secondaryAddress) && isset($secondaryAddress['postalCode']) && !empty($secondaryAddress['postalCode']) ? $secondaryAddress['postalCode'] : ''; ?>" placeholder="Enter Postal Code">
                                        </div>
                                        <div class="clearfix"></div>
                                        <div class="form-group col-md-4">
                                            <label for="pspName">Physician Hospital/Site :</label>
                                            <input type="text" class="form-control" name="secondary-hospital" value="<?= isset($secondaryAddress) && isset($secondaryAddress['hospital']) && !empty($secondaryAddress['hospital']) ? $secondaryAddress['hospital'] : ''; ?>" placeholder="Enter Hospital">
                                        </div>

                                        <div class="form-group col-md-4">
                                            <label for="pspName">Physician Notes:</label>
                                            <textarea class="form-control" name="secondary-notes"><?= isset($secondaryAddress) && isset($secondaryAddress['notes']) && !empty($secondaryAddress['notes']) ? $secondaryAddress['notes'] : ''; ?></textarea>
                                        </div>
                                    </div>
                                    <!-- secondary address -->
                                </div>

                                <!-- /.card-body -->
                                <div class="card-footer">
                                    <input type="submit" class="btn btn-primary" name="btnSubmit" value="Submit">

                                    <p class="errormessage">
                                        <?=$error;?>
                                </div>
                            </form>
                        </div>
                        <!-- /.card -->
                    </div>
                </div>
                <!-- /.container-fluid -->
            </div>



        </div>
    </section>
    <script>
        $('#example').dataTable( {
        "order": [],
        // Your other options here...
    } );
            function toggleAddressFields() {
                var checkbox = document.getElementById("checkbox");
                var addressFields = document.getElementById("secondary-address-fields");
    
                if (checkbox.checked) {
                    addressFields.style.display = "flex";
                } 
                else {
                    addressFields.style.display = "none";
                    // // clear secondary address fields:
                    // var inputs = addressFields.getElementsByTagName("input");
                    // var selects = addressFields.getElementsByTagName("select");
                    // var textareas = addressFields.getElementsByTagName("textarea");
    
                    // for (var i = 0; i < inputs.length; i++) {
                    //     inputs[i].value = ''; 
                    // }
                
                    // for (var i = 0; i < selects.length; i++) {
                    //     selects[i].selectedIndex = 0; 
                    // }
                
                    // for (var i = 0; i < textareas.length; i++) {
                    //     textareas[i].value = ''; 
                    // }
                }
            }
            window.onload = function() {
                var textField = document.getElementById('secondary-postalCode');
                var checkBox = document.getElementById('checkbox');
                if (textField.value.trim() !== '') {
                    checkBox.checked = true;
                } else {
                    checkBox.checked = false;
                }
                toggleAddressFields();
            };
    </script>
    <?php
 include('footer.php'); 
ob_flush();