<?php
    $file       = "jadwal.json";
    $jsondata   = file_get_contents($file);
    $data       = json_decode($jsondata, true);
    $jsondata   = file_get_contents("data.json");
    $data1      = json_decode($jsondata,true);   
    $no         = getMax($data);

    function getMax($arr) {
        if(!empty($arr)){
            $jar    = array();
            foreach ($arr as $vals) {
                array_push($jar,$vals["id"]);
            }
            return max($jar);
        }else{
            return 0;
        }
        
    }

    function date_compare_asc($arg1,$arg2){
        return (int)$arg1['date'] - (int)$arg2['date'];
    }

    function date_compare_dsc($arg1,$arg2){
        return (int)$arg2['date'] - (int)$arg1['date'];
    } 

    if(isset($_GET["old"]) or isset($_GET["ongoing"])){
        usort($data, 'date_compare_asc');
    }else{
        usort($data, 'date_compare_dsc');
    }
    
    

    //START
        if($_GET['schedule']=="delete"){
            $id = isset($_GET['id'])?$_GET['id']:NULL;
            if($id != NULL){
                foreach ($data as $key => $d) {
                    $d['id'];
                    // Hapus data kedua
                    if ($d['id'] == $id) {
                        array_splice($data, $key, 1);
                        $avail      = true;
                    }
                }

                if(!$avail){
                    echo '<script> location.replace("?schedule"); </script>>';
                }
                $jsonfile = json_encode($data, JSON_PRETTY_PRINT);
                $data = file_put_contents($file, $jsonfile);
                echo '<script> location.replace("?schedule"); </script>>';
            }else{
                echo '<script> location.replace("?schedule"); </script>>';
            }
        }else if($_GET['schedule'] == "edit"){
            $id = isset($_GET['id'])?$_GET['id']:NULL;
            if($id != NULL){
                foreach ($data as $key => $d) {
                    if ($d['id'] == $id) {
                        $bandId     = $d['bandId'];
                        $event      = $d['event'];
                        $keterangan = $d['keterangan'];
                        $date       = $d['date'];
                        $avail      = true;
                    }
                }

                if(!$avail){
                    echo '<script> location.replace("?schedule"); </script>>';
                }
            }else{
                echo '<script> location.replace("?schedule"); </script>>';
            }

            if(isset($_POST['save'])){
                $bandId     = isset($_POST['bandId'])?$_POST['bandId']:"";
                $event      = isset($_POST['event'])?$_POST['event']:"";
                $date       = isset($_POST['date'])?$_POST['date']:"";
                $keterangan = isset($_POST['keterangan'])?$_POST['keterangan']:"";

                $d = DateTime::createFromFormat('Y-m-d H:i:s', $date.' 00:00:00');
                if ($d === false) {
                    die("Incorrect date string");
                } else {
                    $date = $d->getTimestamp();
                }
               
                foreach ($data as $key => $d) {
                    if ($d['id'] == $id) {
                        $data[$key]['bandId']         = $bandId;
                        $data[$key]['event']          = $event;
                        $data[$key]['date']           = $date;
                        $data[$key]['keterangan']     = $keterangan;
                    }
                }
                $jsonfile = json_encode($data, JSON_PRETTY_PRINT);
                $data = file_put_contents($file, $jsonfile);
                echo '<script> location.replace("?schedule"); </script>>';
            }
?>
        <div class="card">
            <div class="card-header ">
                <h4>Edit Schedule</h4>
            </div>
            <div class="card-body ">
                <form class="form" method="post">
                    <div class="form-group">
                        <div class="row">
                            <div class="col-4">   
                                <label for="band" class="mr-sm-2">Band Name:</label>
                                <select class="form-control" id="band" name="bandId">
                                <?php
                                    foreach ($data1 as $key => $d) {
                                        if($d['status'] != 2){
                                            $id         = $d['id'];
                                            $nama       = $d['nama'];
                                            $status     = statusName($d['status']);
                                            if($bandId == $id){
                                                echo "<option selected value='$id'>$nama - $status</option>";
                                            }else{
                                                echo "<option value='$id'>$nama - $status</option>";
                                            }
                                        }
                                    }
                                ?>
                                </select>
                            </div>
                            <div class="col-4">   
                                <label for="status" class="mr-sm-2">Status:</label>
                                <select class="form-control" id="status" name="event">
                                    <option <?php if($event == 0) echo "selected"?> value="0">TRIAL</option>
                                    <option <?php if($event == 1) echo "selected"?> value="1">REGULAR</option>
                                    <option <?php if($event == 2) echo "selected"?> value="2">BIRTHDAY</option>
                                    <option <?php if($event == 3) echo "selected"?> value="3">WEDDING</option>
                                </select>
                            </div>
                            <div class="col-4">   
                                <label for="date" class="mr-sm-2">Date:</label>
                                <input type="date" class="form-control mb-2 mr-sm-2" id="date" name="date" required="" value="<?php echo date('Y-m-d',(int)$date)?>">
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-12">
                                <label for="comment" >Additional Info:</label>
                                <textarea class="form-control" placeholder="Info Tambahan" rows="5" name="keterangan" id="comment">
<?php echo $keterangan;?></textarea>
                            </div>
                        </div>
                        <br>
                        <button type="submit" class="btn btn-primary btn-block" name="save">SAVE</button>
                        <a href="?schedule" id="cancel"  class="btn btn-danger btn-block">CANCEL</a>
                    </div>
                </form>
            </div>
<?php
        }else if($_GET['schedule'] == "add"){
            if(isset($_POST['save'])){
                $bandId = isset($_POST['bandId'])?$_POST['bandId']:"";
                $event = isset($_POST['event'])?$_POST['event']:"";
                $date = isset($_POST['date'])?$_POST['date']:"";
                $keterangan = isset($_POST['keterangan'])?$_POST['keterangan']:"";

                $d = DateTime::createFromFormat('Y-m-d H:i:s', $date.' 00:00:00');
                if ($d === false) {
                    die("Incorrect date string");
                } else {
                    $date = $d->getTimestamp();
                }
                $no++;

                // Data array baru
                $data [] = array(
                    'id'    => $no,
                    'bandId'  => $bandId,
                    'event'    => $event,
                    'date' => $date,
                    'keterangan' => $keterangan
                );

                // Mengencode data menjadi json
                $jsonfile = json_encode($data, JSON_PRETTY_PRINT);
    
                // Menyimpan data ke dalam anggota.json
                $data = file_put_contents($file, $jsonfile);

                if($data){
                    echo '<script> location.replace("?schedule"); </script>>';
                }else{
                    echo "ERROR!";
                }
            }
?>
        <div class="card">
            <div class="card-header ">
                <h4>Add Schedule</h4>
            </div>
            <div class="card-body ">
                <form class="form" method="post">
                    <div class="form-group">
                        <div class="row">
                            <div class="col-4">   
                                <label for="band" class="mr-sm-2">Band Name:</label>
                                <select class="form-control" id="band" name="bandId">
                                <?php
                                    foreach ($data1 as $key => $d) {
                                        if($d['status'] != 2){
                                            $id         = $d['id'];
                                            $nama       = $d['nama'];
                                            $status     = statusName($d['status']);
                                            echo "<option value='$id'>$nama - $status</option>";
                                        }
                                    }
                                ?>
                                </select>
                            </div>
                            <div class="col-4">   
                                <label for="status" class="mr-sm-2">Status:</label>
                                <select class="form-control" id="status" name="event">
                                    <option value="0">TRIAL</option>
                                    <option value="1">REGULAR</option>
                                    <option value="2">BIRTHDAY</option>
                                    <option value="3">WEDDING</option>
                                </select>
                            </div>
                            <div class="col-4">   
                                <label for="date" class="mr-sm-2">Date:</label>
                                <input type="date" class="form-control mb-2 mr-sm-2" id="date" name="date" required="" >
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-12">
                                <label for="comment" >Additional Info:</label>
                                <textarea class="form-control" placeholder="Info Tambahan" rows="5" name="keterangan" id="comment"></textarea>
                            </div>
                        </div>
                        <br>
                        <button type="submit" class="btn btn-primary btn-block" name="save">SAVE</button>
                        <a href="?schedule" id="cancel"  class="btn btn-danger btn-block">CANCEL</a>
                    </div>
                </form>
            </div>
<?php
        } else {
?>
    <div class="card">
        <div class="card-header ">
            <h4>SCHEDULE</h4>
        </div>
        <div class="card-body ">
        <form class="form" method="post">
            <div class="form-group">
                <div class="row">
                    <div class="col-md-4">
                    </div>
                    <div class="col-md-4">
                        <a href="<?php echo "?schedule=add";?>" name="start" class="btn btn-primary btn-block" >Add Schedule</a>
					</div>
                    <div class="col-md-4">
                    </div>
                </div>
                <hr>
                <div class="text-center">
                <a href="<?php echo "?schedule&ongoing";?>" name="start" class="btn btn-link " >On Going Date</a> | 
                    <a href="<?php echo "?schedule";?>" name="start" class="btn btn-link " >Latest Date</a> | 
                    <a href="<?php echo "?schedule&old";?>" name="start" class="btn btn-link " >Oldest Date</a>
                </div>
                <hr>
                <div class="row justify-content-center">
                    <div class="col-md">
                    </div>
                    <div class="col-md-10">
                        <div class="table-responsive">
                            <table class="table table-striped" style="text-align: center;">
                                <thead>
                                    <tr>
                                        <th scope="col">#</th>
                                        <th scope="col">Band Name</th>
                                        <th scope="col">PIC</th>
                                        <th scope="col">EVENT</th>
                                        <th scope="col">DATE</th>
                                        <th scope="col">ACTION</th>
                                    </tr>
                                </thead>
                                <tbody>
                                <?php $no=1;foreach($data as $value){

                                    if(isset($_GET['ongoing'])){
                                        $date = date("Y-m-d",(int)$value['date']);
                                        $now = date("Y-m-d"); 
                                        if($date >= $now) {
                                            foreach ($data1 as $key => $d) {
                                                if ($d['id'] == $value['bandId']) {
                                                    $nama       = $d['nama'];
                                                    $pic        = $d['pic'];
                                                    $keterangan = $d['keterangan'];
                                                    $kontak     = $d['kontak'];
                                                    $status     = statusName($d['status']);
                                                    $event      = eventName($value['event']);
                                                    $tanggal = dateFormat($value['date']);
                                                    echo "<tr>";
                                                    echo "<th scope='row'>$no</th>";
                                                    echo "<td style='text-align: left;''>".$nama." - ".$status."</td>";
                                                    echo "<td>".$pic."</td>";
                                                    echo "<td>".$event."</td>";
                                                    echo "<td>".$tanggal."</td>";
                                                    echo "<td><a class='text-primary' href='?schedule=edit&id=".$value['id']."'><i class='far fa-edit'></i></a>&nbsp;&nbsp;|&nbsp;&nbsp;<a class='text-primary' data-toggle='modal' data-target='#confirm-delete' href='#' data-href='?schedule=delete&id=".$value['id']."'><i class='far fa-trash-alt'></i></a></td>";
                                                    echo "</tr>";
                                                    $no++;
                                                }
                                            } 
                                        }  
                                    }else{
                                        foreach ($data1 as $key => $d) {
                                            if ($d['id'] == $value['bandId']) {
                                                $nama       = $d['nama'];
                                                $pic        = $d['pic'];
                                                $keterangan = $d['keterangan'];
                                                $kontak     = $d['kontak'];
                                                $status     = statusName($d['status']);
                                                $tanggal    = dateFormat($value['date']);
                                                $event      = eventName($value['event']);
                                                echo "<tr>";
                                                echo "<th scope='row'>$no</th>";
                                                echo "<td style='text-align: left;''>".$nama." - ".$status."</td>";
                                                echo "<td>".$pic."</td>";
                                                echo "<td>".$event."</td>";
                                                echo "<td>".$tanggal."</td>";
                                                echo "<td><a class='text-primary' href='?schedule=edit&id=".$value['id']."'><i class='far fa-edit'></i></a>&nbsp;&nbsp;|&nbsp;&nbsp;<a class='text-primary' data-toggle='modal' data-target='#confirm-delete' href='#' data-href='?schedule=delete&id=".$value['id']."'><i class='far fa-trash-alt'></i></a></td>";
                                                echo "</tr>";
                                                $no++;
                                            }
                                        }        
                                     }
                                       
                                }
                                ?>
      
                                
                                </tbody>
                            </table>
                        </div>
                    </div>
                    <div class="col-md">
                    </div>
                </div>
                <hr>   
            </div>
        </form>
    </div>
    <!-- The Modal -->
    <div class="modal fade" id="confirm-delete">
        <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
        
            <!-- Modal Header -->
            <div class="modal-header">
            <h4 class="modal-title">Confirm Delete</h4>
            <button type="button" class="close" data-dismiss="modal">&times;</button>
            </div>
            
            <!-- Modal body -->
            <div class="modal-body">
            This Process cannot be undone.</br>
            Do you want to proceed?
            </div>
            
            <!-- Modal footer -->
            <div class="modal-footer">
            <button type="button" class="btn btn-outline-secondary" data-dismiss="modal">Close</button>
            <a type="button" class="btn btn-danger btn-ok">Delete</a>
            </div>
            
        </div>
        </div>
    </div>
    <script>
        $('#confirm-delete').on('show.bs.modal', function(e) {
            $(this).find('.btn-ok').attr('href', $(e.relatedTarget).data('href'));
            
            $('.debug-url').html('Delete URL: <strong>' + $(this).find('.btn-ok').attr('href') + '</strong>');
        });
    </script>
<?php
    }
?>