<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Dashboard</title>
    <!--<meta name="description" content="Lawn Mower - Petrol" />-->
    <!--<meta name="keywords" content="LAWN MOWER petrol" />-->
    <!--<meta name="robots" content="INDEX,FOLLOW" />-->
    <link rel="icon" href="https://www.completehire.com.au/media/favicon/default/ch_1.png" type="image/x-icon" />
    <link rel="shortcut icon" href="https://www.completehire.com.au/media/favicon/default/ch_1.png"
        type="image/x-icon" />

    <link rel="stylesheet" type="text/css"
        href="https://www.completehire.com.au/media/css/e9411e85deedf5303a337838822a58d8-1-SSL-1586867774.css?6560019944e61" />
    <link rel="stylesheet" type="text/css"
        href="https://www.completehire.com.au/media/css/c2c1964ba379ccf27d2a5b16848e750b-1-SSL-1688620731.css?6560019944e61"
        media="all" />
    <script type="text/javascript"src="test.js"></script>
    <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Anton" />
    <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Heebo:300,400,500,700" />
    <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Raleway:300,400,500,700,600" />
    <link rel="stylesheet" href="test.css" />

    <link rel="stylesheet" type="text/css"
        href="https://www.completehire.com.au/media/css/eed67cf2e1aa2fb3942ef5ada5c54ac6-1-SSL-1688620581.css?6560019944e61"
        media="all" />

    </script>
    <meta name="viewport" content="initial-scale=1.0, width=device-width" />

</head>

<body
    class=" catalog-product-view catalog-product-view product-lawn-mower-petrol-3447 categorypath-products-landscaping category-landscaping">
    <div class="wrapper">
        <!--<noscript>-->
        <!--    <div class="global-site-notice noscript">-->
        <!--        <div class="notice-inner">-->
        <!--            <p>-->
        <!--                <strong>JavaScript seems to be disabled in your browser.</strong><br />-->
        <!--                You must have JavaScript enabled in your browser to utilize the functionality of this website.-->
        <!--            </p>-->
        <!--        </div>-->
        <!--    </div>-->
        <!--</noscript>-->

            <header id="header" class="page-header">
                <div id="page-header-container-new-div" class="page-header-container">
                    <div>
                        <a id="header-logo-a" href="/">
                            <img src="https://www.completehire.com.au/skin/frontend/onewest/default/images/page-elements/CH-logo-header.svg"
                                alt="Complete Hire" class="img-responsive" width="295">
                        </a>
                    </div>
                    <div class = "big_dashboard_text">DASHBOARD</div>

                    <div id="newhomepage-nav-outer-div">
                        <!-- Navigation -->
                        <div id="header-nav" class="skip-content newhomepage-nav">

                       </div>

                </div>
            </header>
</body>

</html>
<?php
    /* Database credentials.*/
    define('DB_SERVER', 'localhost');
    define('DB_USERNAME', 'itiseasy_chire2');
    define('DB_PASSWORD', 'cMr~ezrpG.@)');
    define('DB_NAME', 'itiseasy_chire2');
    
    /* Stripe stuff */
    require_once "vendor/stripe/stripe-php/init.php";
    $stripe = new \Stripe\StripeClient('sk_test_51OCubSK8ETdQ9853uIY4vlOdAG5p8fvkfmuRu1IlMsUUzlvNGVIecfBKbTGKxF43Z3xzQAEoGkAC9QNxN9kdUpTs00CYRQmCkw');
    
    /* Twilio stuff */
    require __DIR__ . '/vendor/autoload.php';
    use Twilio\Rest\Client;
    // Your Account SID and Auth Token from twilio.com/console - To set up environmental variables, see http://twil.io/secure
    $account_sid = 'AC9a6d95862d239c1171eb772891e39bfd';
    $auth_token = 'eef4e312e34ca48a7953459792fe4acd';
    // In production, these should be environment variables. E.g.: $auth_token = $_ENV["TWILIO_AUTH_TOKEN"]
    $twilio_number = "+18643517156";

    /* Attempt to connect to MySQL database */
    $link = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_NAME);
     
    // Check connection
    if($link === false){
        die("ERROR: Could not connect. " . mysqli_connect_error());
    }
    
   $sql = 'SELECT * FROM bookings';
   //mysqli_select_db($link,'chire_test1');
   $retval = mysqli_query( $link, $sql );

   
   if(! $retval ) {
      die('Could not get data: ' . mysql_error());
   }

    echo "<h1 class = 'processed_h1'>------------------  New Bookings  ------------------</h1>";
    echo "<div class = 'maximo_div'><ul>";


   while($row = mysqli_fetch_array($retval, MYSQLI_ASSOC)) {
        $this_row = $row['request_id'];
        $last_processed = "";
        
        if (isset($_GET[$this_row])){
            $last_processed = $this_row;
            
                if ($_GET[$this_row] == "false") {
                    // make sure email only goes to one person
                    if (!str_contains($row['email'], ',')) {
                        $subject = 'Complete Hire Booking Update';
                        $message = "
                        <html>
                        
                        <body>
                        
                            <header style='
                                width: 100%;
                                border-top: 1px solid #fe811f;
                                border-bottom: 1px solid #fe811f;
                                border-left: 1px solid #fe811f;
                                border-right: 1px solid #fe811f;
                                padding: 20px 20px;
                                background: #023b82;'>
                                
                                <div id='page-header-container-new-div' style='
                                    display: flex;
                                    flex-direction: row;
                                    justify-content: space-between;'>
                                    
                                    <div>
                                        <a id='header-logo-a' href='https://www.completehire.com.au/'>
                                            <img src='https://www.completehire.com.au/skin/frontend/onewest/default/images/page-elements/CH-logo-header.svg'
                                                alt='Complete Hire' class='img-responsive' width='295'>
                                        </a>
                                    </div>
                        
                                    <div style='
                                        color: white;
                                        font-size: 2rem;
                                        padding-left: 20px;
                                        padding-right: 20px;'>BOOKING UPDATE
                                    </div>
                        
                                </div>
                            </header>
                        
                            <p><b>Thank you for your booking {$row['full_name']}</b></p>
                            <br>
                            <p>We have recieved your booking and have declined it (for now) {insert reason}.</p>
                            <br>
                            <p>If you would like to get in touch. {insert complete hire phone number, email, contact details}</p>
                        </body>
                        
                        </html>
                        ";
                        
                        // To send HTML mail, the Content-type header must be set
                        $headers[] = 'MIME-Version: 1.0';
                        $headers[] = 'Content-type: text/html; charset=iso-8859-1';
                        
                        // Mail it
                        mail($row['email'], $subject, $message, implode("\r\n", $headers));
                    }
                    
                    // change number to customer number when twilio account is upgraded
                    //$customer_mobile = '+61' . $row['mobile'];
                    $customer_mobile = '+61' . '0474224211';
                    
                    $client = new Client($account_sid, $auth_token);
                    // $client->messages->create(
                    //     // Where to send a text message (your cell phone?)
                    //     $customer_mobile,
                    //     array(
                    //         'from' => $twilio_number,
                    //         'body' => 'Complete Hire Update: Your booking has been declined. {insert more detail}'
                    //     )
                    // );
                
                }
            
            if ($_GET[$this_row] != "false"){
                //update user id and product price
            	global $stripe;
            	
            	$c_id = $row['customer_id'];
            	if ($c_id == NULL) {
            	   $test_customer = $stripe->customers->create([ 
                    'email' => $row['email'],
                    'name' => $row['full_name'],
                    'phone' => $row['mobile'],
                   ]);
                   $sql_update_customer = "UPDATE bookings SET customer_id = '$test_customer->id' WHERE request_id = $this_row;";
                   $something = mysqli_query( $link, $sql_update_customer );
            	} else {
            	    $test_customer = $stripe->customers->retrieve(
            	        $c_id,
            	        []
            	   );
            	}

                $p_id = $row['product_id'];
                $test_product = $stripe->products->retrieve(
                    $p_id,
                    []
                );

                $test_price = $stripe->prices->search([
                  'query' => "product: '$p_id'",
                ]);
                $price_id = $test_price['data'][0]->id;

                //find the date differences
                $start_hire = strtotime($row['start_hire']);
                $end_hire = strtotime($row['end_hire']);
                $hire_length_in_days = ($end_hire-$start_hire)/86400;
                
                $sql_update_accept = "UPDATE bookings SET status = 1 WHERE request_id = $this_row;";
                // $sql_update_customer = "UPDATE bookings SET customer_id = '$test_customer->id' WHERE request_id = $this_row;";
                
                
                $something = mysqli_query( $link, $sql_update_accept );
                // $something = mysqli_query( $link, $sql_update_customer );


               if(! $something ) {
                    die('Could not get data: ' . mysql_error());
                }

                $shipping_rate = "";
                foreach ($stripe->shippingRates->all() as $s_rate){
                    if($s_rate->id == $_GET['s_rates']){
                        $shipping_rate = $s_rate->id;
                    }
                }
                
                $invoice = $stripe->invoices->create([
                    'customer' => $test_customer->id,
                    'currency' => "aud",
                    'shipping_cost' => ['shipping_rate' => "$shipping_rate"],
                    //'price' => "price_1OEkZuK8ETdQ98530ZjRZs58",
                    'collection_method'=>"send_invoice",
                    'days_until_due'=>5,
                ]);
                
                $discount_rate = $_GET['discounts'];
                if ($discount_rate != 0) {
                    $test_discount = $stripe->coupons->create([
                      'percent_off' => $discount_rate,
                      'duration' => 'once',
                    ]);
                    $invoiceItem = $stripe->invoiceItems->create([
                      'customer' => $test_customer->id,
                      'invoice' => $invoice->id,
                      'price' => $price_id,
                      'quantity' => $hire_length_in_days,
                      'discounts' => [['coupon'=>"$test_discount->id"]]
                    ]);
                }
                else{
                  $invoiceItem = $stripe->invoiceItems->create([
                  'customer' => $test_customer->id,
                  'invoice' => $invoice->id,
                  'price' => $price_id,
                  'quantity' => $hire_length_in_days,
                  //'discounts' => [['coupon'=>"$test_discount->id"]]
                ]);
                }
                
                // echo $invoice;
                $invoice->sendInvoice();
                
                if (!str_contains($row['email'], ',')) {
                    $subject = 'Complete Hire Booking Accepted';
                    $message = "
                    <html>
                    
                    <body>
                    
                        <header style='
                            width: 100%;
                            border-top: 1px solid #fe811f;
                            border-bottom: 1px solid #fe811f;
                            border-left: 1px solid #fe811f;
                            border-right: 1px solid #fe811f;
                            padding: 20px 20px;
                            background: #023b82;'>
                            
                            <div id='page-header-container-new-div' style='
                                display: flex;
                                flex-direction: row;
                                justify-content: space-between;'>
                                
                                <div>
                                    <a id='header-logo-a' href='https://www.completehire.com.au/'>
                                        <img src='https://www.completehire.com.au/skin/frontend/onewest/default/images/page-elements/CH-logo-header.svg'
                                            alt='Complete Hire' class='img-responsive' width='295'>
                                    </a>
                                </div>
                    
                                <div style='
                                    color: white;
                                    font-size: 2rem;
                                    padding-left: 20px;
                                    padding-right: 20px;'>BOOKING ACCEPTED
                                </div>
                    
                            </div>
                        </header>
                    
                        <p><b>Thank you for your booking {$row['full_name']}</b></p>
                        <br>
                        <p>We have recieved your booking and have accepted it. You will recieve an invoice emailed to you shortly.{on live (stripe)}</p>
                        <br>
                        <p>Here are the details.{insert details}</p>
                        <br>
                        <p>If you would like to get in touch. {insert complete hire phone number, email, contact details}</p>
                    </body>
                    
                    </html>
                    ";
                    
                    // To send HTML mail, the Content-type header must be set
                    $headers[] = 'MIME-Version: 1.0';
                    $headers[] = 'Content-type: text/html; charset=iso-8859-1';
                    
                    // Mail it
                    mail($row['email'], $subject, $message, implode("\r\n", $headers));
                }
                
                // change number to customer number when twilio account is upgraded
                //$customer_mobile = '+61' . $row['mobile'];
                $customer_mobile = '+61' . '0474224211';
                
                $client = new Client($account_sid, $auth_token);
                // $client->messages->create(
                //     // Where to send a text message (your cell phone?)
                //     $customer_mobile,
                //     array(
                //         'from' => $twilio_number,
                //         'body' => 'Complete Hire Update: Your booking has been accepted. {insert more detail}'
                //     )
                // );

            }
            
            $sql_update_accept = "UPDATE bookings SET processed = 1 WHERE request_id = $this_row";
            $something = mysqli_query( $link, $sql_update_accept );
               if(! $something ) {
                    die('Could not get data: ' . mysql_error());
                }
                
        }

       if($row['processed']==0 && $last_processed!=$this_row){
            $p_id = $row['product_id'];
            $test_product = $stripe->products->retrieve(
                $p_id,
                []
            );
                $test_price = $stripe->prices->search([
                  'query' => "product: '$p_id'"
                ]);
                $price_id = $test_price['data'][0]->id;
            $current_price = $test_price['data'][0]->unit_amount;
            
            $start_hire = strtotime($row['start_hire']);
            $end_hire = strtotime($row['end_hire']);
            
            $hire_length_in_days = ($end_hire-$start_hire)/86400;
            
            $value = ($current_price/100)*$hire_length_in_days;
            
            $img_url = $test_product->images[0];

           echo "<li><div class = 'top-div'><span>{$row['full_name']}</span><span>$test_product->name</span><div class = 'arrow'><span class = 'l-span'></span><span class = 'r-span'></span></div></div><div class = 'bottom-div'>
            <table>
            <tr>
                <td>
                
            <div><label>Name:</label> {$row['full_name']}</div>
            <div><label>Mobile:</label> {$row['mobile']}</div>
            <div><label>Email:</label> {$row['email']}</div>
           <div> <label>Location:</label> {$row['location_of_hire']}</div>
             <div><label>Dates:</label> {$row['start_hire']} to  {$row['end_hire']}</div>
             <div> <label>Notes:</label> {$row['notes']}</div>

             <div>
              <form method = 'get' name = 'form' action = '?$this_row=true'>
              <input type = 'hidden' name = '$this_row' value = 'true'>
              <label for='t_cost'>Total Cost:</label>

              <!-- <input type='text' value = '$value' id='t_cost' name='t_cost'> -->
              <span>$value</span>
              
              <br>
              <label for='s_rates'>Shipping:</label>
            <select name='s_rates' id='s_rates'>
                
            ";
            
            foreach($stripe->shippingRates->all() as $s_rate){
                echo"<option value='$s_rate->id'>$s_rate->display_name</option>";
            }
            echo "
            </select>
            <br>
            
            <label for='discounts'>Discount (%):</label>
            <select name='discounts' id='discounts' value='1'>
            ";
            
            $discount_array = array(0, 5, 10, 15, 20);
            
            foreach($discount_array as $d){
                echo"<option value='$d'>$d</option>";
            }
            echo "
            </select>
            
            
            <br>
            <input class = 'random_class' type='submit' value = 'Accept'>
            </form>
            <a href = '?$this_row=false'><button>Decline</button></a>
            
            </td>


            </div></tr>
            <tr>

            </tr>
            </table></li>";
            
       }
      
   }
   
   echo "</ul><h1 class = 'processed_h1'>------------------  Processed  ------------------</h1><ul><table>
    <tr>
        <th><b>Name</b></th>
        <th><b>Number</b></th>
        <th><b>Email</b></th>
        <th><b>Address</b></th>
        <th><b>Status</b></th>
    </tr>";
   $retval = mysqli_query( $link, $sql );
   while($new_row = mysqli_fetch_array($retval, MYSQLI_ASSOC)) {
       if($new_row['processed']==1){
           echo "<tr>";
           
           if($new_row['status']==1){
               echo "<td><label>{$new_row['full_name']}</td></label>
               <td><label>{$new_row['mobile']}</td></label>
               <td><label>{$new_row['email']}</td></label>
                <td><label>{$new_row['location_of_hire']}</td></label>
               <td><span style = 'color:green'>Accepted</span></td></tr>";
           }else{
               echo "<td><label>{$new_row['full_name']}</td></label>
               <td><label>{$new_row['mobile']}</td></label>
               <td><label>{$new_row['email']}</td></label>
                <td><label>{$new_row['location_of_hire']}</td></label>
                <td><span style = 'color:red'>Declined</span></td></tr>";
           }
           
       }
   }
   echo "</ul></table></div>";
   
   
//     echo "<h1 class = 'processed_h1'>------------------  Paid Invoices ------------------</h1>";
    
//     echo "<div class = 'maximo_div'><ul><table>
//     <tr>
//         <th><b>Customer Name</b></th>
//         <th><b>Customer Email</b></th>
//         <th><b>Invoice ID</b></th>
//         <th><b>Customer ID</b></th>
//         <th><b>Amount Due</b></th>
//         <th><b>Amount Paid</b></th>
//         <th><b>Amount Remaining</b></th>
//         <th><b>Status</b></th>
//     </tr>";
//     foreach ($stripe->invoices->all(['status' => 'paid']) as $i){
//         echo "<tr>";
//         // echo $i->status;
        
//         $amount_due_divided = $i['amount_due'] / 100;
//         $amount_paid_divided = $i['amount_paid'] / 100;
//         $amount_remaining_divided = $i['amount_remaining'] / 100;
        
//         echo "
//         <td>{$i['customer_name']}</td>
//         <td>{$i['customer_email']}</td>
//         <td>{$i['id']}</td>
//         <td>{$i['customer']}</td>
//         <td>{$amount_due_divided}</td>
//         <td>{$amount_paid_divided}</td>
//         <td>{$amount_remaining_divided}</td>
//         <td style='color: green'>{$i['status']}</td>
//         ";
//         echo"</tr>";
//     }
//     echo "</table></ul></div>";
    
    
    
//     echo "<h1 class = 'processed_h1'>------------------  Open Invoices ------------------</h1>";
    
//     echo "<div class = 'maximo_div'><ul><table>
//     <tr>
//         <th><b>Customer Name</b></th>
//         <th><b>Customer Email</b></th>
//         <th><b>Invoice ID</b></th>
//         <th><b>Customer ID</b></th>
//         <th><b>Amount Due</b></th>
//         <th><b>Amount Paid</b></th>
//         <th><b>Amount Remaining</b></th>
//         <th><b>Status</b></th>
//     </tr>";
//     // $count = 0;
//     foreach ($stripe->invoices->all(['limit' => 200, 'status' => 'open']) as $i){
//         // $count++;
//         echo "<tr>";
//         // echo $i->status;
        
//         $amount_due_divided = $i['amount_due'] / 100;
//         $amount_paid_divided = $i['amount_paid'] / 100;
//         $amount_remaining_divided = $i['amount_remaining'] / 100;
        
//         echo "
//         <td>{$i['customer_name']}</td>
//         <td>{$i['customer_email']}</td>
//         <td>{$i['id']}</td>
//         <td>{$i['customer']}</td>
//         <td>{$amount_due_divided}</td>
//         <td>{$amount_paid_divided}</td>
//         <td>{$amount_remaining_divided}</td>
//         <td style='color: blue'>{$i['status']}</td>
//         ";
//         echo"</tr>";
//     }
//     echo "</table></ul></div>";
//     // echo $count + '(should be at least 130) | currently being limited to 100 by stripe';
    
//   $sql_credit_forms = 'SELECT * FROM credit_forms';
//   //mysqli_select_db($link,'chire_test1');
//   $retval2 = mysqli_query( $link, $sql_credit_forms );
   
//   if(! $retval2 ) {
//       die('Could not get data: ' . mysql_error());
//   }
   
//   echo "<h1 class = 'processed_h1'>------------------  Credit Forms ------------------</h1>";
   
//   echo "<div class = 'maximo_div'><ul><table>
//       <tr>
//         <th><b>Business Structure</b></th>
//         <th><b>Years in Business</b></th>
//         <th><b>Business Name</b></th>
//         <th><b>Trading Name</b></th>
//         <th><b>A.C.N</b></th>
//         <th><b>A.B.N</b></th>
//         <th><b>Business Address</b></th>
//         <th><b>Postal Address</b></th>
//         <th><b>Telephone</b></th>
//         <th><b>Mobile</b></th>
//         <th><b>Email</b></th>
//     </tr>";
   
//   while($row2 = mysqli_fetch_array($retval2, MYSQLI_ASSOC)) {
//         echo "<tr>";
//         $bstructure = array("Public Co.", "Sole Trader", "Pty Ltd Co.", "Partnership");
//         echo "
//         <td>{$bstructure[$row2['b_structure']-1]}</td>
//         <td>{$row2['b_years']}</td>
//         <td>{$row2['b_name']}</td>
//         <td>{$row2['t_name']}</td>
//         <td>{$row2['c_acn_name']}</td>
//         <td>{$row2['c_abn_name']}</td>
//         <td>{$row2['b_address']}</td>
//         <td>{$row2['p_address']}</td>
//         <td>{$row2['t_phone']}</td>
//         <td>{$row2['m_phone']}</td>
//         <td>{$row2['email']}</td>
//         ";
//         echo"</tr>";
//   }
//     echo "</table></ul></div>";
    
    
//     echo "<h1 class = 'processed_h1'>------------------  Customers ------------------</h1>";
    
//     echo "<div class = 'maximo_div'><ul><table>
//     <tr>
//         <th><b>Customer Name</b></th>
//         <th><b>ID</b></th>
//         <th><b>Invoice Prefix</b></th>
//         <th><b>Email</b></th>
//         <th><b>Phone</b></th>
//     </tr>";
//     foreach ($stripe->customers->all(['limit' => 10]) as $c){
//         echo "<tr>
//         <td>{$c['name']}</td>
//         <td>{$c['id']}</td>
//         <td>{$c['invoice_prefix']}</td>
//         <td>{$c['email']}</td>
//         <td>{$c['phone']}</td>
//         ";
//         echo"</tr>";
//     }
//     echo "</table></ul></div>";
    
    
    
//     echo "<h1 class = 'processed_h1'>------------------  Customers (better) ------------------</h1>";
    
    
//     echo "<div class = 'maximo_div'>
//     <ul>
//     <table style='color: #023b82'>
//         <tr>
//             <th style='width: 20vw'>Name</th>
//             <th style='width: 20vw'>Customer ID</th>
//             <th style='width: 20vw'>Invoice Prefix</th>
//             <th style='width: 20vw'>Email</th>
//             <th style='width: 20vw'>Phone</th>
//         </tr>
//     </table>";
    
//     foreach ($stripe->customers->all(['limit' => 20]) as $c){
    
//     echo "<li>
    
//     <div class = 'top-div'>
//         <table style='color: white;'>
//             <tr>
//                 <td style='width: 20vw'>{$c['name']}</td>
//                 <td style='width: 20vw'>{$c['id']}</td>
//                 <td style='width: 20vw'>{$c['invoice_prefix']}</td>
//                 <td style='width: 20vw'>{$c['email']}</td>
//                 <td style='width: 20vw'>{$c['phone']}</td>
//                 <td>&#8889;</td>
//             </tr>
//         </table>
//     </div>
    
//     <div class = 'bottom-div'>";
    
//     echo "
//     <table>
//     <tr>
//         <th><b>Customer Name</b></th>
//         <th><b>Customer Email</b></th>
//         <th><b>Invoice ID</b></th>
//         <th><b>Customer ID</b></th>
//         <th><b>Amount Due</b></th>
//         <th><b>Amount Paid</b></th>
//         <th><b>Amount Remaining</b></th>
//         <th><b>Status</b></th>
//     </tr>";
    
//     foreach ($stripe->invoices->all(['customer' => $c['id']]) as $i) {
//         if ($i['status'] == 'open') {
//             $test = 'blue';
//         } else if ($i['status'] == 'paid') {
//             $test = 'green';
//         }
        
//         $amount_due_divided = $i['amount_due'] / 100;
//         $amount_paid_divided = $i['amount_paid'] / 100;
//         $amount_remaining_divided = $i['amount_remaining'] / 100;
        
//         echo "
//         <tr>
//         <td>{$i['customer_name']}</td>
//         <td>{$i['customer_email']}</td>
//         <td>{$i['id']}</td>
//         <td>{$i['customer']}</td>
//         <td>{$amount_due_divided}</td>
//         <td>{$amount_paid_divided}</td>
//         <td>{$amount_remaining_divided}</td>
//         <td style='color: {$test}'>{$i['status']}</td>
//         </tr>";
//     }
    
//     echo "</table></div>
    
//     </li>";
//     }
//     echo "</ul></div>";
    
    
    echo "<h1 class = 'processed_h1'>-------------- Search Test (/ command)-----------------</h1>";
    
    echo "<div class = 'maximo_div'>
    <ul>";
    
    echo "
    
    <form action='dashboard_test4.php' method='post'>
        <label for='search_bar'>Search customers and invoices</label>
        <br />
        <input type='text' name='search_bar' />
        <input class='random_class' type='submit' value='Search' />
    </form>";

    
    if(isset($_POST['search_bar']) && $_POST['search_bar'] != '') {
        $search_input = $_POST['search_bar'];
        
        // $search_print = $stripe->customers->search([
        //   'query' => "name: '$test_value'",
        // ]);
        
        // echo $search_print['data'][0]->name;
        // echo $search_print['data'][0];
        
        
        
        // echo "   
        // <table style='color: #023b82'>
        //     <tr>
        //         <th style='width: 20vw'><b>Name</b></th>
        //         <th style='width: 20vw'><b>Customer ID</b></th>
        //         <th style='width: 20vw'><b>Invoice Prefix</b></th>
        //         <th style='width: 20vw'><b>Email</b></th>
        //         <th style='width: 20vw'><b>Phone</b></th>
        //     </tr>
        // </table>";
        if (str_starts_with($search_input, '/')) {
            $trimmed_input = ltrim($search_input, $search_input[0]);
    
            $valid_input_array = array("paid", "open", "draft", "void", "uncollectible", "overdue");
            
            echo "
            <li>
            <table>
            <tr>
                <th><b>Customer Name</b></th>
                <th><b>Customer Email</b></th>
                <th><b>Invoice ID</b></th>
                <th><b>Customer ID</b></th>
                <th><b>Amount Due</b></th>
                <th><b>Amount Paid</b></th>
                <th><b>Amount Remaining</b></th>
                <th><b>Status</b></th>
            </tr>";
            
            if (in_array($trimmed_input, $valid_input_array)) {
                if ($trimmed_input != "overdue") {
                    foreach ($stripe->invoices->all(['limit' => 20, 'status' => $trimmed_input]) as $i) {
                        
                            if ($i['status'] == 'open') {
                                $test = 'blue';
                            } else if ($i['status'] == 'paid') {
                                $test = 'green';
                            } else if ($i['status'] == 'void') {
                                $test = 'black';
                            }
                            
                            $amount_due_divided = $i['amount_due'] / 100;
                            $amount_paid_divided = $i['amount_paid'] / 100;
                            $amount_remaining_divided = $i['amount_remaining'] / 100;
                            
                            echo "
                            <tr>
                            <td>{$i['customer_name']}</td>
                            <td>{$i['customer_email']}</td>
                            <td>{$i['id']}</td>
                            <td>{$i['customer']}</td>
                            <td>{$amount_due_divided}</td>
                            <td>{$amount_paid_divided}</td>
                            <td>{$amount_remaining_divided}</td>
                            <td style='color: {$test}'>{$i['status']}</td>
                            </tr>";
                        }
                        
                        echo "</table></div>
                        
                        </li>";
                } else {
                    foreach ($stripe->invoices->all(['limit' => 20, 'status' => 'open','due_date' => ['lte' => time()]]) as $i) {
                        
                        $amount_due_divided = $i['amount_due'] / 100;
                        $amount_paid_divided = $i['amount_paid'] / 100;
                        $amount_remaining_divided = $i['amount_remaining'] / 100;
                        
                        echo "
                        <tr>
                        <td>{$i['customer_name']}</td>
                        <td>{$i['customer_email']}</td>
                        <td>{$i['id']}</td>
                        <td>{$i['customer']}</td>
                        <td>{$amount_due_divided}</td>
                        <td>{$amount_paid_divided}</td>
                        <td>{$amount_remaining_divided}</td>
                        <td style='color: red'>overdue</td>
                        </tr>";
                    }
                    
                    echo "</table></div>
                    
                    </li>";
                }
                
            } else {
                echo "invalid input";
            }
        
        } else if (str_starts_with($search_input, 'in_')) {
            $search_invoice_id = $stripe->invoices->retrieve(
              $search_input,
              []
            );
            echo "
            <li>
            <table>
                <tr>
                    <th><b>Customer Name</b></th>
                    <th><b>Customer Email</b></th>
                    <th><b>Invoice ID</b></th>
                    <th><b>Customer ID</b></th>
                    <th><b>Amount Due</b></th>
                    <th><b>Amount Paid</b></th>
                    <th><b>Amount Remaining</b></th>
                    <th><b>Status</b></th>
                </tr>";

                    echo "<tr>";
                    // echo $i->status;
                    
                    $amount_due_divided = $search_invoice_id['amount_due'] / 100;
                    $amount_paid_divided = $search_invoice_id['amount_paid'] / 100;
                    $amount_remaining_divided = $search_invoice_id['amount_remaining'] / 100;
                    
                    echo "
                    <td>{$search_invoice_id['customer_name']}</td>
                    <td>{$search_invoice_id['customer_email']}</td>
                    <td>{$search_invoice_id['id']}</td>
                    <td>{$search_invoice_id['customer']}</td>
                    <td>{$amount_due_divided}</td>
                    <td>{$amount_paid_divided}</td>
                    <td>{$amount_remaining_divided}</td>
                    <td style='color: green'>{$search_invoice_id['status']}</td>
                    ";
                    echo"</tr>";
                
                echo "</table></li>";
        
        } else if (str_starts_with($search_input, 'cus_')) {
            $search_customer_id = $stripe->customers->retrieve(
              $search_input,
              []
            );
            
            echo "   
            <table style='color: #023b82'>
                <tr>
                    <th style='width: 20vw'><b>Name</b></th>
                    <th style='width: 20vw'><b>Customer ID</b></th>
                    <th style='width: 20vw'><b>Invoice Prefix</b></th>
                    <th style='width: 20vw'><b>Email</b></th>
                    <th style='width: 20vw'><b>Phone</b></th>
                </tr>
            </table>";
            
            echo "<li>
            
            <div class = 'top-div'>
                <table style='color: white;'>
                    <tr>
                        <td style='width: 20vw'>{$search_customer_id['name']}</td>
                        <td style='width: 20vw'>{$search_customer_id['id']}</td>
                        <td style='width: 20vw'>{$search_customer_id['invoice_prefix']}</td>
                        <td style='width: 20vw'>{$search_customer_id['email']}</td>
                        <td style='width: 20vw'>{$search_customer_id['phone']}</td>
                        <td>&#8889;</td>
                    </tr>
                </table>
            </div>
            
            <div class = 'bottom-div'>";
            
            echo "
            <table>
            <tr>
                <th><b>Customer Name</b></th>
                <th><b>Customer Email</b></th>
                <th><b>Invoice ID</b></th>
                <th><b>Customer ID</b></th>
                <th><b>Amount Due</b></th>
                <th><b>Amount Paid</b></th>
                <th><b>Amount Remaining</b></th>
                <th><b>Status</b></th>
            </tr>";
            
            foreach ($stripe->invoices->all(['customer' => $search_customer_id['id']]) as $i) {
                if ($i['status'] == 'open') {
                    $test = 'blue';
                } else if ($i['status'] == 'paid') {
                    $test = 'green';
                }
                
                $amount_due_divided = $i['amount_due'] / 100;
                $amount_paid_divided = $i['amount_paid'] / 100;
                $amount_remaining_divided = $i['amount_remaining'] / 100;
                
                echo "
                <tr>
                <td>{$i['customer_name']}</td>
                <td>{$i['customer_email']}</td>
                <td>{$i['id']}</td>
                <td>{$i['customer']}</td>
                <td>{$amount_due_divided}</td>
                <td>{$amount_paid_divided}</td>
                <td>{$amount_remaining_divided}</td>
                <td style='color: {$test}'>{$i['status']}</td>
                </tr>";
            }
            
            echo "</table></div>
            
            </li>";
        } else {
        
            if (str_contains($search_input, '@')) {
                $what_search = 'email';
            } else if (str_starts_with($search_input, '04')) {
                // probably need to do this better
                $what_search = 'phone';
            } else {
                $what_search = 'name';
            }
            
            echo "   
            <table style='color: #023b82'>
                <tr>
                    <th style='width: 20vw'><b>Name</b></th>
                    <th style='width: 20vw'><b>Customer ID</b></th>
                    <th style='width: 20vw'><b>Invoice Prefix</b></th>
                    <th style='width: 20vw'><b>Email</b></th>
                    <th style='width: 20vw'><b>Phone</b></th>
                </tr>
            </table>";
            
            
            foreach ($stripe->customers->search(['query' => "$what_search: '$search_input'", 'limit' => 100]) as $result) {
                // echo $result['id'];
                // echo "<br />";
                // echo $result;
                
                echo "<li>
                
                <div class = 'top-div'>
                    <table style='color: white;'>
                        <tr>
                            <td style='width: 20vw'>{$result['name']}</td>
                            <td style='width: 20vw'>{$result['id']}</td>
                            <td style='width: 20vw'>{$result['invoice_prefix']}</td>
                            <td style='width: 20vw'>{$result['email']}</td>
                            <td style='width: 20vw'>{$result['phone']}</td>
                            <td>&#8889;</td>
                        </tr>
                    </table>
                </div>
                
                <div class = 'bottom-div'>";
                
                echo "
                <table>
                <tr>
                    <th><b>Customer Name</b></th>
                    <th><b>Customer Email</b></th>
                    <th><b>Description</b></th>
                    <th><b>Invoice ID</b></th>
                    <th><b>Customer ID</b></th>
                    <th><b>Amount Due</b></th>
                    <th><b>Amount Paid</b></th>
                    <th><b>Amount Remaining</b></th>
                    <th><b>Status</b></th>
                </tr>";
                
                foreach ($stripe->invoices->all(['customer' => $result['id']]) as $i) {
                    if ($i['status'] == 'open') {
                        $test = 'blue';
                    } else if ($i['status'] == 'paid') {
                        $test = 'green';
                        
                        $customer_to_update = $stripe->customers->retrieve(
                          $result['id'],
                          []
                        );
                        
                        if ($customer_to_update->invoice_settings->default_payment_method == null) {
                            $payment_intent = $stripe->paymentIntents->retrieve($i->payment_intent, []);
                            echo $payment_intent->payment_method;
                            
                            $stripe->customers->update(
                              $result['id'],
                              ['invoice_settings' => ['default_payment_method' => $payment_intent->payment_method]]
                            );
                            
                        }
                        
                    }
                    
                    $amount_due_divided = $i['amount_due'] / 100;
                    $amount_paid_divided = $i['amount_paid'] / 100;
                    $amount_remaining_divided = $i['amount_remaining'] / 100;
                    
                    echo "
                    <tr>
                    <td>{$i['customer_name']}</td>
                    <td>{$i['customer_email']}</td>
                    <td>{$i->lines->data[0]['description']}</td>
                    <td>{$i['id']}</td>
                    <td>{$i['customer']}</td>
                    <td>{$amount_due_divided}</td>
                    <td>{$amount_paid_divided}</td>
                    <td>{$amount_remaining_divided}</td>
                    <td style='color: {$test}'>{$i['status']}</td>
                    <!-- $i->payment_intent -->
                    </tr>";
                    
                    // $payment_intent = $stripe->paymentIntents->retrieve('pi_3OK91OK8ETdQ98531rFcJCHI', []);
                }
                    // echo $payment_intent->payment_method;
                
                echo "</table></div>
                
                </li>";
            
                
            }
        
        }
        
    }
    
    echo "</ul></div>";
    
    
    
    echo "<h1 class = 'processed_h1'>----------------- Deposit Creation Test -------------------</h1>";
    
    echo "<div class = 'maximo_div'>
    <ul>";
    
    echo "
    
    <form action='dashboard_test4.php' method='post'>
        <h2>Create deposit (for new customer)</h2>
        
        <br />
        
        <label for='desposit_desc'>Deposit for: (few word description of product)</label>
        <br />
        <input type='text' name='desposit_desc' />
        
        <br />
        <br />
        
        <label for='deposit_amount'>Deposit Amount: (in dollars no dollar sign, eg 450)</label>
        <br />
        <input type='text' name='deposit_amount' />
        
        <br />
        <br />
        
        <input class='random_class' style='width: 150px' type='submit' value='Create Deposit' />
    </form>";
    
    
    
    if(isset($_POST['desposit_desc']) && $_POST['desposit_desc'] != '' && isset($_POST['deposit_amount']) && $_POST['deposit_amount'] != '') {
        
        $deposit_amount = ($_POST['deposit_amount'] * 100);
        $deposit_product_name = "Deposit for " . $_POST['desposit_desc'];
        
        $test_price = $stripe->prices->create([
          'unit_amount' => $deposit_amount,
          'currency' => 'aud',
          'product_data' => ['name' => $deposit_product_name],
        ]);
        
        $test_plink = $stripe->paymentLinks->create([
          'line_items' => [
            [
              'price' => $test_price->id,
              'quantity' => 1,
            ],
          ],
          'billing_address_collection' => 'required',
          'customer_creation' => 'always',
          'phone_number_collection' => ['enabled' => 'true'],
        //   'after_completion' => ['hosted_confirmation' => [0 => $test_custom_message],],
          'submit_type' => 'book',
          'payment_intent_data' => ['setup_future_usage' => 'off_session'],
          'invoice_creation' => ['enabled' => 'true'],
        //   "setup_future_usage": "off_session"
        ]);
        
        echo "<label>Stripe URL:</label>" + $test_plink->url;
    }
    
    echo "</ul></div>";
    
    // $deposit_amount = 4000;
    // $deposit_product_desc = "archive222";
    // $deposit_product_name = "Deposit for " . $deposit_product_desc;
    
    // $test_custom_message = 'Complete Hire: Thank you for your deposit.';
    
    // $test_price = $stripe->prices->create([
    //   'unit_amount' => $deposit_amount,
    //   'currency' => 'aud',
    //   'product_data' => ['name' => $deposit_product_name],
    // ]);
    
    
    // $test_plink = $stripe->paymentLinks->create([
    //   'line_items' => [
    //     [
    //       'price' => $test_price->id,
    //       'quantity' => 1,
    //     ],
    //   ],
    //   'billing_address_collection' => 'required',
    //   'customer_creation' => 'always',
    //   'phone_number_collection' => ['enabled' => 'true'],
    // //   'after_completion' => ['hosted_confirmation' => [0 => $test_custom_message],],
    //   'submit_type' => 'book',
    //   'payment_intent_data' => ['setup_future_usage' => 'off_session'],
    //   'invoice_creation' => ['enabled' => 'true'],
    // //   "setup_future_usage": "off_session"
    // ]);
    
    
    /* Important */
    // var_dump($test_plink->after_completion->hosted_confirmation[0]);
    
    
    // echo $test_plink->url;
    
    
    
    
    /* 
        set up webhook or event listener of some kind to:
            archive product when payment completed
            set customer default_payment_method when payment completed and invoice made
        
    */
    
    // $stripe->products->update(
    //   $test_price->product,
    //   ['active' => 'false']
    // );
    
    // echo '<br>product archived';
    
    echo "<h1 class = 'processed_h1'>----------------- Existing Customer Deposit -------------------</h1>";
    
    echo "<div class = 'maximo_div'>
    <ul>";
    
    echo "
    
    <form action='dashboard_test4.php' method='post'>
        <h2>Create deposit (for existing customer)</h2>
        
        <br />
        
        <label for='new_desposit_desc'>Deposit for: (few word description of product)</label>
        <br />
        <input type='text' name='new_desposit_desc' />
        
        <br />
        <br />
        
        <label for='new_deposit_amount'>Deposit Amount: (in dollars no dollar sign, eg 450)</label>
        <br />
        <input type='text' name='new_deposit_amount' />
        
        <br />
        <br />
        
        <label for='customer_id_input'>Customer ID:</label>
        <p>cus_P8PrTh1dxlT4l7</p>
        <br />
        <input type='text' name='customer_id_input' />
        
        <br />
        <br />
        
        <input class='random_class' style='width: 200px' type='submit' value='Create New Deposit' />
    </form>";
    
    if(isset($_POST['new_desposit_desc']) && $_POST['new_desposit_desc'] != '' && isset($_POST['new_deposit_amount']) && $_POST['new_deposit_amount'] != '') {

        $new_deposit_amount = ($_POST['new_deposit_amount'] * 100);
        $new_deposit_product_name = "Deposit for " . $_POST['new_desposit_desc'];
        
        $customer_id_input = $_POST['customer_id_input'];
        
        // try {
            $get_customer = $stripe->customers->retrieve(
                $customer_id_input,
                []
            );
            
            // echo $get_customer->invoice_settings->default_payment_method;
            
            $test_price = $stripe->prices->create([
              'unit_amount' => $new_deposit_amount,
              'currency' => 'aud',
              'product_data' => ['name' => $new_deposit_product_name],
            ]);
            
            /* auto_advance might have worked, but finalise might have worked too idk */
            $deposit_invoice = $stripe->invoices->create([
                'customer' => $customer_id_input,
                'currency' => "aud",
                'collection_method'=>"charge_automatically",
                // 'auto_advance' => 'true',
                // 'days_until_due'=>1,
                'default_payment_method' => $get_customer->invoice_settings->default_payment_method,
            ]);
            
            $invoiceItem = $stripe->invoiceItems->create([
              'customer' => $customer_id_input,
              'invoice' => $deposit_invoice->id,
              'price' => $test_price->id,
              'quantity' => 1,
            ]);
            
            $stripe->invoices->finalizeInvoice($deposit_invoice->id, []);
            
            
            // $deposit_invoice->sendInvoice();
            
            echo $deposit_invoice . "\n";
            
            echo $deposit_invoice->hosted_invoice_url;
            
        // } catch (Exception $e) {
        //     echo "Could not find customer";
        // }
        
    }
        
    echo "</ul></div>";
    
    echo "<h1 class = 'processed_h1'>---------------------------------------------</h1>";
    
    
   
   mysqli_close($link);
   echo "<script type='text/javascript'
        src='test.js'></script>";
?>
